-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphysin.js
More file actions
7336 lines (7318 loc) · 275 KB
/
Copy pathphysin.js
File metadata and controls
7336 lines (7318 loc) · 275 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PhysiN 0.1.0 -- N-dimensional rigid body dynamics for three.js.
* https://github.com/ (MIT)
*
* Single file containing algebra, shapes, mass properties, the
* integrator, collision detection, the solver, the 4D slice and the
* three.js plugin.
*
* HOW TO USE IT, as with physi.js:
* 1. Load three.js, then load this file with a <script> tag.
* 2. Point PhysiN.scripts.worker at the worker file:
* PhysiN.scripts.worker = 'physiN_worker.js';
* Leave it as null to run the physics in the main thread.
* 3. Use PhysiN.Scene in the place of THREE.Scene.
* 4. Use PhysiN.BoxMesh, PhysiN.SphereMesh, PhysiN.ConvexMesh,
* PhysiN.TorusMesh or PhysiN.PlaneMesh in the place of THREE.Mesh.
* For four dimensions and more, use PhysiN.HyperBoxMesh,
* PhysiN.HyperSphereMesh, PhysiN.HyperTorusMesh, PhysiN.HyperMesh or
* PhysiN.HyperPlaneMesh.
* 5. Call scene.simulate(timeStep, maxSubSteps) at each frame.
*
* CAUTION for four dimensions and more: the angular velocity, the torque and
* the angular momentum are BIVECTORS with n(n-1)/2 components. They are not
* vectors. The orientation is a ROTOR with 2^(n-1) components. It is not a
* quaternion. See the README.
*
* HOW TO READ THIS FILE. The `// src/...` lines show the modules. Three type
* blocks give the names that all of the other code uses:
* `Dims` above `dims()`, in src/nd/core/dims.js
* `Shape` above `HyperBox()`, in src/nd/body/shapes.js
* `Contact` above `makeContact()`, in src/nd/detect/collide.js
* ND-PHYSICS.md holds the mathematics, and the blocks below point to it by
* the number of its parts, for example "A3" or "B2".
*
* CAUTION for a change: physiN_worker.js holds the same engine modules as
* this file, word for word. It leaves out only the code that a worker does
* not use. Make the same change in the two files.
*/
(() => {
// The two helpers of the bundler. They build the namespace objects, such as
// `PhysiN.nd` and `PhysiN.slice`, from a table of getters.
var __defProp = Object.defineProperty;
/** Puts a getter on `target` for each name in `all`. */
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/nd/index.js
var nd_exports = {};
__export(nd_exports, {
Body: () => Body,
ConvexMesh: () => ConvexMesh,
HalfSpace: () => HalfSpace,
HyperBox: () => HyperBox,
HyperSphere: () => HyperSphere,
Torus: () => Torus,
World: () => World,
accumulateDrift: () => accumulateDrift,
angularError: () => angularError,
angularMass: () => angularMass,
ballVolume: () => ballVolume,
boxBoxAxis: () => boxBoxAxis,
boxVertices: () => boxVertices,
buildContactGraph: () => buildContactGraph,
collide: () => collide,
commutator: () => commutator,
commutatorMatrix: () => commutatorMatrix,
contractVecBi: () => contractVecBi,
createConstraint: () => createConstraint,
defaultParams: () => defaultParams,
dims: () => dims,
hingeAngle: () => hingeAngle,
hyperBoxInertia: () => hyperBoxInertia,
hyperBoxMesh: () => hyperBoxMesh,
hyperSphereInertia: () => hyperSphereInertia,
inertiaFromCovariance: () => inertiaFromCovariance,
integratePositions: () => integratePositions,
integrateVelocities: () => integrateVelocities,
linalg: () => linalg_exports,
massProperties: () => massProperties,
mv: () => multivector_exports,
orthoComplement: () => orthoComplement,
prepareContact: () => prepareContact,
prepareRows: () => prepareRows,
refreshComplement: () => refreshComplement,
resetConstraint: () => resetConstraint,
rotor: () => rotor_exports,
shockPropagation: () => shockPropagation,
solveContact: () => solveContact,
solveJoint: () => solveJoint,
starMatrix: () => starMatrix,
tangentBasis: () => tangentBasis,
torusCovariance: () => torusCovariance,
torusInertia: () => torusInertia,
torusMesh: () => torusMesh,
torusVolume: () => torusVolume,
warmStart: () => warmStart,
warmStartJoint: () => warmStartJoint,
wedgeVec: () => wedgeVec
});
// src/nd/core/dims.js
/**
* The constant tables of the geometric algebra of `n` dimensions.
*
* A multivector has `N = 2^n` components. The index of a component is a bit
* mask of the axes of its blade. Bit `i` is set when the axis `i` is in the
* blade. Thus index 0 is the scalar, index `1 << i` is the axis `i`, and
* index `(1 << i) | (1 << j)` is the plane of the axes `i` and `j`.
*
* Three lengths are in use through the library. Each array is flat.
* `n` a vector: the position, the velocity, the force
* `k` a bivector: the angular velocity, the torque, the momentum
* `r` a rotor: the orientation
* A matrix is flat and row major. See ND-PHYSICS.md, A1.
*
* @typedef {object} Dims
* @property {number} n the count of dimensions. It is 2 or more.
* @property {number} k the count of bivector components, `n (n-1) / 2`
* @property {number} r the count of rotor components, `2^(n-1)`
* @property {number} N the count of multivector components, `2^n`
* @property {Int8Array} grade the grade of each blade, of length `N`
* @property {Int8Array} reverseSign the sign that the reverse gives to a blade
* @property {Int32Array} gpBlade the blade of a geometric product, `N` by `N`
* @property {Int8Array} gpSign the sign of a geometric product, `N` by `N`
* @property {Int32Array} vecBlade the blade of each axis, of length `n`
* @property {number[][]} pairs the two axes of each bivector component
* @property {number[]} biBlade the blade of each bivector component
* @property {Int32Array} biOfBlade the bivector component of a blade, or -1
* @property {number[]} evenBlade the blade of each rotor component
* @property {Int32Array} slotOfBlade the rotor component of a blade, or -1
* @property {Int32Array} evenGpSlot the component of a rotor product, `r` by `r`
* @property {Int8Array} evenGpSign the sign of a rotor product, `r` by `r`
* @property {number} scalarSlot the rotor component that holds the scalar
* @property {Int32Array} biSlot the rotor component of a bivector component
* @property {Float64Array} comm the commutator table, `k` by `k` by `k`
* @property {Float64Array[]} eStar the star matrix of each axis, each `k` by `n`
* @property {number} cXX a diagonal term of the canonical simplex covariance
* @property {number} cXY an off diagonal term of the same covariance
* @property {number} simplexVolumeDiv the divisor `n!` of a simplex volume
* @property {number} simplexMomentDiv the divisor `(n+1)!` of a simplex moment
*/
/** The tables of each `n` that `dims()` built before. */
var cache = /* @__PURE__ */ new Map();
/** The count of the bits that are set in `x`. This is the grade of a blade. */
function popcount(x) {
let c = 0;
while (x !== 0) {
x &= x - 1;
c += 1;
}
return c;
}
/** The factorial `m!`. It is 1 when `m` is 0 or less. */
function factorial(m) {
let f = 1;
for (let i = 2; i <= m; i += 1) f *= i;
return f;
}
/**
* The tables of the algebra of `n` dimensions. Build them one time, then
* give the same object `D` to each function of the library.
*
* The sign of a product of two blades comes from the count of the swaps that
* put the axes in order. The commutator table `comm` and the star matrices
* `eStar` come from those signs. See ND-PHYSICS.md, A1, A2 and C4.
*
* The result is in a cache. Two calls with the same `n` give the same
* object. Do not change the tables.
*
* @param {number} n the count of dimensions. It must be an integer, 2 or more.
* @returns {Dims} the tables
* @throws {Error} when `n` is not an integer of 2 or more
*/
function dims(n) {
if (!Number.isInteger(n) || n < 2) throw new Error("dims: n must be an integer of 2 or more");
if (cache.has(n)) return cache.get(n);
const N = 1 << n;
// The grade of a blade is the count of its axes. The reverse turns the
// order of the axes around. That gives the sign (-1)^(g (g-1) / 2).
const grade = new Int8Array(N);
const reverseSign = new Int8Array(N);
for (let m = 0; m < N; m += 1) {
const g = popcount(m);
grade[m] = g;
reverseSign[m] = g * (g - 1) / 2 & 1 ? -1 : 1;
}
// The geometric product of two blades. The blade of the result is the
// exclusive or of the two masks. The sign comes from the count of the
// swaps that put the axes back in order.
const gpBlade = new Int32Array(N * N);
const gpSign = new Int8Array(N * N);
for (let a = 0; a < N; a += 1) {
for (let b = 0; b < N; b += 1) {
let m = a >> 1;
let swaps = 0;
while (m !== 0) {
swaps += popcount(m & b);
m >>= 1;
}
gpBlade[a * N + b] = a ^ b;
gpSign[a * N + b] = swaps & 1 ? -1 : 1;
}
}
const vecBlade = new Int32Array(n);
for (let i = 0; i < n; i += 1) vecBlade[i] = 1 << i;
// The bivector components, in lexicographic order of the axis pair. This
// order is a free choice, but the library keeps it everywhere.
const pairs = [];
const biBlade = [];
const biOfBlade = new Int32Array(N).fill(-1);
for (let i = 0; i < n; i += 1) {
for (let j = i + 1; j < n; j += 1) {
biOfBlade[1 << i | 1 << j] = pairs.length;
pairs.push([i, j]);
biBlade.push(1 << i | 1 << j);
}
}
const k = pairs.length;
// A rotor holds only the blades of even grade: 0, 2, 4, and so on. Give
// each one a slot. In 4 dimensions this gives 8 slots, not 4.
const evenBlade = [];
const slotOfBlade = new Int32Array(N).fill(-1);
for (let m = 0; m < N; m += 1) {
if ((grade[m] & 1) === 0) {
slotOfBlade[m] = evenBlade.length;
evenBlade.push(m);
}
}
const r = evenBlade.length;
// The geometric product of two rotors stays in the even sub algebra. Cut
// the full `N` by `N` table down to `r` by `r`, and `rotorMul` is fast.
const evenGpSlot = new Int32Array(r * r);
const evenGpSign = new Int8Array(r * r);
for (let a = 0; a < r; a += 1) {
for (let b = 0; b < r; b += 1) {
const idx = evenBlade[a] * N + evenBlade[b];
evenGpSlot[a * r + b] = slotOfBlade[gpBlade[idx]];
evenGpSign[a * r + b] = gpSign[idx];
}
}
const scalarSlot = slotOfBlade[0];
const biSlot = new Int32Array(k);
for (let p = 0; p < k; p += 1) biSlot[p] = slotOfBlade[biBlade[p]];
// The commutator `A x B = (A B - B A) / 2` of two bivectors. The result is
// again a bivector. `comm[(p * k + q) * k + s]` is the part of the product
// of the components `p` and `q` that goes to the component `s`. The
// gyroscopic term uses this table. See ND-PHYSICS.md, A2 and A7.
const comm = new Float64Array(k * k * k);
for (let p = 0; p < k; p += 1) {
for (let q = 0; q < k; q += 1) {
const ab = biBlade[p] * N + biBlade[q];
const ba = biBlade[q] * N + biBlade[p];
if (gpBlade[ab] === gpBlade[ba]) {
const s = biOfBlade[gpBlade[ab]];
if (s >= 0) {
comm[(p * k + q) * k + s] += (gpSign[ab] - gpSign[ba]) / 2;
}
}
}
}
// The star matrix of each axis vector. `starMatrix` of any vector `r` is
// the sum of `r[i] * eStar[i]`. `starProducts` uses these to build the
// inertia tensor. See ND-PHYSICS.md, A3.
const eStar = [];
for (let i = 0; i < n; i += 1) {
const S = new Float64Array(k * n);
for (let p = 0; p < k; p += 1) {
const [a, b] = pairs[p];
if (a === i) S[p * n + b] += 1;
if (b === i) S[p * n + a] -= 1;
}
eStar.push(S);
}
const D = {
n,
k,
r,
N,
grade,
reverseSign,
gpBlade,
gpSign,
vecBlade,
pairs,
biBlade,
biOfBlade,
evenBlade,
slotOfBlade,
evenGpSlot,
evenGpSign,
scalarSlot,
biSlot,
comm,
eStar,
// Canonical simplex covariance values of Part A, step A8.
cXX: 2 / factorial(n + 2),
cXY: 1 / factorial(n + 2),
simplexVolumeDiv: factorial(n),
simplexMomentDiv: factorial(n + 1)
};
cache.set(n, D);
return D;
}
// src/nd/core/linalg.js
//
// Small dense matrix work. The sides are `n` (2 to 6) or `k` (1 to 15), thus
// a plain loop is faster than a library.
//
// The convention of the whole library: a matrix is a flat `Float64Array` in
// row major order. The element of the row `i` and the column `j` of a matrix
// of `cols` columns is at `A[i * cols + j]`. An array does not hold its own
// shape. The caller gives the row count and the column count.
//
// Each function takes an optional `out` buffer. It writes into that buffer
// and gives it back. Give a buffer to keep the step free of garbage.
var linalg_exports = {};
__export(linalg_exports, {
jacobiEigen: () => jacobiEigen,
matDet: () => matDet,
matIdentity: () => matIdentity,
matInverse: () => matInverse,
matInverseSPD: () => matInverseSPD,
matMul: () => matMul,
matMulT: () => matMulT,
matTVec: () => matTVec,
matTranspose: () => matTranspose,
matVec: () => matVec,
matZero: () => matZero
});
/** A new matrix of `rows` by `cols`. All of its elements are zero. */
function matZero(rows, cols) {
return new Float64Array(rows * cols);
}
/** The identity matrix of `m` by `m`. It writes into `out` when you give it. */
function matIdentity(m, out) {
const A = out || matZero(m, m);
A.fill(0);
for (let i = 0; i < m; i += 1) A[i * m + i] = 1;
return A;
}
/**
* The product `A B`. `A` is `ra` by `ca`, and `B` is `ca` by `cb`.
* The loop skips a zero element of `A`, because the inertia tensor and the
* rotor matrices hold many zeros.
* @returns {Float64Array} the product, `ra` by `cb`
*/
function matMul(A, B, ra, ca, cb, out) {
const C = out || matZero(ra, cb);
C.fill(0);
for (let i = 0; i < ra; i += 1) {
for (let t = 0; t < ca; t += 1) {
const a = A[i * ca + t];
if (a === 0) continue;
for (let j = 0; j < cb; j += 1) C[i * cb + j] += a * B[t * cb + j];
}
}
return C;
}
/**
* The product `A B^T`. `A` is `ra` by `ca`, and `B` is `rb` by `ca`.
* With `matMul` this gives the change of frame `[R]2 I [R]2^T` of the
* inertia tensor. See ND-PHYSICS.md, A6.
* @returns {Float64Array} the product, `ra` by `rb`
*/
function matMulT(A, B, ra, ca, rb, out) {
const C = out || matZero(ra, rb);
C.fill(0);
for (let i = 0; i < ra; i += 1) {
for (let j = 0; j < rb; j += 1) {
let s = 0;
for (let t = 0; t < ca; t += 1) s += A[i * ca + t] * B[j * ca + t];
C[i * rb + j] = s;
}
}
return C;
}
/** The product `A x`. `A` is `rows` by `cols`. It gives a vector of `rows`. */
function matVec(A, x, rows, cols, out) {
const y = out || new Float64Array(rows);
for (let i = 0; i < rows; i += 1) {
let s = 0;
for (let j = 0; j < cols; j += 1) s += A[i * cols + j] * x[j];
y[i] = s;
}
return y;
}
/**
* The product `A^T x`. `A` is `rows` by `cols`, and `x` has `rows`. It gives
* a vector of `cols`. This does not transpose `A` in memory.
*/
function matTVec(A, x, rows, cols, out) {
const y = out || new Float64Array(cols);
y.fill(0);
for (let i = 0; i < rows; i += 1) {
const xi = x[i];
if (xi === 0) continue;
for (let j = 0; j < cols; j += 1) y[j] += A[i * cols + j] * xi;
}
return y;
}
/** The transpose of `A`. `A` is `rows` by `cols`, the result `cols` by `rows`. */
function matTranspose(A, rows, cols, out) {
const B = out || matZero(cols, rows);
for (let i = 0; i < rows; i += 1) for (let j = 0; j < cols; j += 1) B[j * rows + i] = A[i * cols + j];
return B;
}
/**
* The determinant of the matrix `A` of `m` by `m`. It uses Gauss removal
* with a partial pivot. It does not change `A`.
*
* `massProperties` and `orientCells` use the sign of the determinant to find
* the direction of a simplex. See ND-PHYSICS.md, A8.
*
* @returns {number} the determinant. It is 0 when the matrix is singular.
*/
function matDet(A, m) {
const a = Float64Array.from(A);
let det2 = 1;
for (let c = 0; c < m; c += 1) {
let piv = c;
let best = Math.abs(a[c * m + c]);
for (let i = c + 1; i < m; i += 1) {
const v = Math.abs(a[i * m + c]);
if (v > best) {
best = v;
piv = i;
}
}
if (best === 0) return 0;
if (piv !== c) {
for (let j = 0; j < m; j += 1) {
const t = a[c * m + j];
a[c * m + j] = a[piv * m + j];
a[piv * m + j] = t;
}
det2 = -det2;
}
const d = a[c * m + c];
det2 *= d;
for (let i = c + 1; i < m; i += 1) {
const f = a[i * m + c] / d;
if (f === 0) continue;
for (let j = c; j < m; j += 1) a[i * m + j] -= f * a[c * m + j];
}
}
return det2;
}
/**
* The inverse of the matrix `A` of `m` by `m`. It uses Gauss-Jordan removal
* with a partial pivot. It does not change `A`.
*
* Use `matInverseSPD` for an inertia tensor. It is symmetrical and positive
* definite, and Cholesky is faster and more stable.
*
* @throws {Error} when the matrix is singular
*/
function matInverse(A, m, out) {
const a = Float64Array.from(A);
const inv = matIdentity(m, out);
for (let c = 0; c < m; c += 1) {
let piv = c;
let best = Math.abs(a[c * m + c]);
for (let i = c + 1; i < m; i += 1) {
const v = Math.abs(a[i * m + c]);
if (v > best) {
best = v;
piv = i;
}
}
if (best < 1e-300) throw new Error("matInverse: the matrix is singular");
if (piv !== c) {
for (let j = 0; j < m; j += 1) {
let t = a[c * m + j];
a[c * m + j] = a[piv * m + j];
a[piv * m + j] = t;
t = inv[c * m + j];
inv[c * m + j] = inv[piv * m + j];
inv[piv * m + j] = t;
}
}
const d = a[c * m + c];
for (let j = 0; j < m; j += 1) {
a[c * m + j] /= d;
inv[c * m + j] /= d;
}
for (let i = 0; i < m; i += 1) {
if (i === c) continue;
const f = a[i * m + c];
if (f === 0) continue;
for (let j = 0; j < m; j += 1) {
a[i * m + j] -= f * a[c * m + j];
inv[i * m + j] -= f * inv[c * m + j];
}
}
}
return inv;
}
/**
* The inverse of a symmetrical positive definite matrix of `m` by `m`. This
* is the usual condition of an inertia tensor.
*
* The three steps: cut `A` into `L L^T` with Cholesky, invert the lower
* triangle `L`, then give `A^-1 = L^-T L^-1`. The result is symmetrical.
*
* A body that is flat in one axis can give a matrix that is not positive
* definite. In that condition the function falls back to `matInverse`.
*/
function matInverseSPD(A, m, out) {
const L = matZero(m, m);
for (let i = 0; i < m; i += 1) {
for (let j = 0; j <= i; j += 1) {
let s = A[i * m + j];
for (let t = 0; t < j; t += 1) s -= L[i * m + t] * L[j * m + t];
if (i === j) {
if (s <= 0) return matInverse(A, m, out);
L[i * m + j] = Math.sqrt(s);
} else {
L[i * m + j] = s / L[j * m + j];
}
}
}
const Li = matZero(m, m);
for (let i = 0; i < m; i += 1) {
Li[i * m + i] = 1 / L[i * m + i];
for (let j = 0; j < i; j += 1) {
let s = 0;
for (let t = j; t < i; t += 1) s += L[i * m + t] * Li[t * m + j];
Li[i * m + j] = -s * Li[i * m + i];
}
}
const inv = out || matZero(m, m);
inv.fill(0);
for (let i = 0; i < m; i += 1) {
for (let j = 0; j <= i; j += 1) {
let s = 0;
for (let t = i; t < m; t += 1) s += Li[t * m + i] * Li[t * m + j];
inv[i * m + j] = s;
inv[j * m + i] = s;
}
}
return inv;
}
/**
* The eigenvalues and the eigenvectors of a symmetrical matrix of `m` by
* `m`. It uses the cyclic Jacobi method. Each turn of the loop makes one
* pair of off diagonal elements zero. It stops when the sum of the squares
* of the off diagonal elements is very small, or after `sweeps` turns.
*
* This is a tool for a test and for analysis. The step does not use it.
*
* @returns {{values: Float64Array, vectors: Float64Array}} the eigenvalues,
* of length `m`, and the eigenvectors as the columns of an `m` by `m`
* matrix. The values are not in order.
*/
function jacobiEigen(A, m, sweeps = 60) {
const a = Float64Array.from(A);
const V = matIdentity(m);
for (let s = 0; s < sweeps; s += 1) {
let off = 0;
for (let i = 0; i < m; i += 1) for (let j = i + 1; j < m; j += 1) off += a[i * m + j] * a[i * m + j];
if (off < 1e-30) break;
for (let p = 0; p < m; p += 1) {
for (let q = p + 1; q < m; q += 1) {
const apq = a[p * m + q];
if (Math.abs(apq) < 1e-300) continue;
const theta = (a[q * m + q] - a[p * m + p]) / (2 * apq);
const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1));
const c = 1 / Math.sqrt(t * t + 1);
const sn = t * c;
for (let i = 0; i < m; i += 1) {
const aip = a[i * m + p];
const aiq = a[i * m + q];
a[i * m + p] = c * aip - sn * aiq;
a[i * m + q] = sn * aip + c * aiq;
}
for (let i = 0; i < m; i += 1) {
const api = a[p * m + i];
const aqi = a[q * m + i];
a[p * m + i] = c * api - sn * aqi;
a[q * m + i] = sn * api + c * aqi;
}
for (let i = 0; i < m; i += 1) {
const vip = V[i * m + p];
const viq = V[i * m + q];
V[i * m + p] = c * vip - sn * viq;
V[i * m + q] = sn * vip + c * viq;
}
}
}
}
const values = new Float64Array(m);
for (let i = 0; i < m; i += 1) values[i] = a[i * m + i];
return { values, vectors: V };
}
// src/nd/algebra/multivector.js
//
// The full multivector of `N = 2^n` components. The index of a component is
// the bit mask of its blade, as `dims()` gives it.
//
// A multivector is large. The step does not use one. The three small types
// (vector, bivector, rotor) do the work of each frame. Use a multivector
// only to build a table, or for an operation that mixes the grades, such as
// the wedge product of the separating axis test.
//
// The `mvFrom*` and `mvTo*` functions move between the small types and the
// full multivector. See ND-PHYSICS.md, A1 and A2.
var multivector_exports = {};
__export(multivector_exports, {
mvContract: () => mvContract,
mvDual: () => mvDual,
mvFromBivector: () => mvFromBivector,
mvFromRotor: () => mvFromRotor,
mvFromVector: () => mvFromVector,
mvGp: () => mvGp,
mvGrade: () => mvGrade,
mvNorm: () => mvNorm,
mvReverse: () => mvReverse,
mvToBivector: () => mvToBivector,
mvToRotor: () => mvToRotor,
mvToVector: () => mvToVector,
mvWedge: () => mvWedge,
mvZero: () => mvZero
});
/** A new multivector of `N` components. All of them are zero. */
function mvZero(D) {
return new Float64Array(D.N);
}
/** Puts the vector `v`, of length `n`, into the grade 1 blades. */
function mvFromVector(D, v, out) {
const M = out || mvZero(D);
M.fill(0);
for (let i = 0; i < D.n; i += 1) M[D.vecBlade[i]] = v[i];
return M;
}
/** Puts the bivector `B`, of length `k`, into the grade 2 blades. */
function mvFromBivector(D, B, out) {
const M = out || mvZero(D);
M.fill(0);
for (let p = 0; p < D.k; p += 1) M[D.biBlade[p]] = B[p];
return M;
}
/** Puts the rotor `R`, of length `r`, into the blades of even grade. */
function mvFromRotor(D, R, out) {
const M = out || mvZero(D);
M.fill(0);
for (let s = 0; s < D.r; s += 1) M[D.evenBlade[s]] = R[s];
return M;
}
/** Takes the grade 1 part of `M` out, as a vector of length `n`. */
function mvToVector(D, M, out) {
const v = out || new Float64Array(D.n);
for (let i = 0; i < D.n; i += 1) v[i] = M[D.vecBlade[i]];
return v;
}
/** Takes the grade 2 part of `M` out, as a bivector of length `k`. */
function mvToBivector(D, M, out) {
const B = out || new Float64Array(D.k);
for (let p = 0; p < D.k; p += 1) B[p] = M[D.biBlade[p]];
return B;
}
/** Takes the even part of `M` out, as a rotor of length `r`. */
function mvToRotor(D, M, out) {
const R = out || new Float64Array(D.r);
for (let s = 0; s < D.r; s += 1) R[s] = M[D.evenBlade[s]];
return R;
}
/**
* The geometric product `A B` of two multivectors. This is the basic
* product of the algebra. For two vectors it gives `a b = a . b + a ^ b`,
* thus the scalar part and the bivector part together.
*
* The rotor sandwich `R x R~` uses two of these products.
*
* @param {Dims} D the tables from `dims(n)`
* @param {Float64Array} A a multivector of `N`
* @param {Float64Array} B a multivector of `N`
* @param {Float64Array} [out] a buffer of `N`. It must not be `A` or `B`.
* @returns {Float64Array} the product
* @throws {Error} when `out` is one of the inputs
*/
function mvGp(D, A, B, out) {
const C = out || mvZero(D);
if (C === A || C === B) throw new Error("mvGp: the output must not be an input");
C.fill(0);
const N = D.N;
for (let a = 0; a < N; a += 1) {
const va = A[a];
if (va === 0) continue;
for (let b = 0; b < N; b += 1) {
const vb = B[b];
if (vb === 0) continue;
const idx = a * N + b;
C[D.gpBlade[idx]] += D.gpSign[idx] * va * vb;
}
}
return C;
}
/**
* The exterior product `A ^ B`. It is the geometric product without the
* terms that hold a common axis, thus the test `(a & b) !== 0`.
*
* The wedge of two vectors gives the plane through them. `boxBoxAxis` wedges
* `n - 1` axes together, then takes the dual, to build a separating axis.
* See ND-PHYSICS.md, A10.
*
* @throws {Error} when `out` is one of the inputs
*/
function mvWedge(D, A, B, out) {
const C = out || mvZero(D);
if (C === A || C === B) throw new Error("mvWedge: the output must not be an input");
C.fill(0);
const N = D.N;
for (let a = 0; a < N; a += 1) {
const va = A[a];
if (va === 0) continue;
for (let b = 0; b < N; b += 1) {
const vb = B[b];
if (vb === 0) continue;
if ((a & b) !== 0) continue;
const idx = a * N + b;
C[a ^ b] += D.gpSign[idx] * va * vb;
}
}
return C;
}
/**
* The left contraction `A . B`. It keeps only the terms in which the blade
* of `A` is fully inside the blade of `B`, thus the test `(a & b) === a`.
* The grade of the result is the grade of `B` less the grade of `A`.
*
* The velocity of a point uses the contraction `r . w` of a vector and a
* bivector. `contractVecBi` does that one operation, and it is faster.
*
* @throws {Error} when `out` is one of the inputs
*/
function mvContract(D, A, B, out) {
const C = out || mvZero(D);
if (C === A || C === B) throw new Error("mvContract: the output must not be an input");
C.fill(0);
const N = D.N;
for (let a = 0; a < N; a += 1) {
const va = A[a];
if (va === 0) continue;
for (let b = 0; b < N; b += 1) {
const vb = B[b];
if (vb === 0) continue;
if ((a & b) !== a) continue;
const idx = a * N + b;
C[a ^ b] += D.gpSign[idx] * va * vb;
}
}
return C;
}
/**
* The reverse `A~`. It turns the order of the axes of each blade around.
* That gives the sign `(-1)^(g (g-1) / 2)` to a blade of the grade `g`.
* For a unit rotor the reverse is the inverse. See ND-PHYSICS.md, A2.
*/
function mvReverse(D, A, out) {
const C = out || mvZero(D);
for (let m = 0; m < D.N; m += 1) C[m] = D.reverseSign[m] * A[m];
return C;
}
/** Keeps the part of `A` of the grade `g`. All other components become zero. */
function mvGrade(D, A, g, out) {
const C = out || mvZero(D);
C.fill(0);
for (let m = 0; m < D.N; m += 1) if (D.grade[m] === g) C[m] = A[m];
return C;
}
/**
* The dual `A I^-1`. `I` is the pseudoscalar, thus the blade of all `n`
* axes, at the index `N - 1`. The dual changes a blade of the grade `g`
* into a blade of the grade `n - g`.
*
* `boxBoxAxis` takes the dual of a blade of the grade `n - 1` to get the
* vector normal to it, and that vector is a separating axis.
*/
function mvDual(D, A, out) {
const C = out || mvZero(D);
C.fill(0);
const I = D.N - 1;
const sInv = D.reverseSign[I];
const N = D.N;
for (let a = 0; a < N; a += 1) {
const va = A[a];
if (va === 0) continue;
const idx = a * N + I;
C[D.gpBlade[idx]] += D.gpSign[idx] * sInv * va;
}
return C;
}
/** The square root of the sum of the squares of all `N` components. */
function mvNorm(D, A) {
let s = 0;
for (let m = 0; m < D.N; m += 1) s += A[m] * A[m];
return Math.sqrt(s);
}
// src/nd/algebra/rotor.js
//
// The orientation of a body is a rotor. A rotor is a member of the even sub
// algebra: it holds only the blades of the grade 0, 2, 4, and so on. It is a
// flat `Float64Array` of `r = 2^(n-1)` components, in the order of
// `D.evenBlade`. `D.scalarSlot` is the component of the scalar.
//
// CAUTION: a rotor is not a quaternion. In 3 dimensions it has 4 components,
// and it acts as a quaternion does. In 4 dimensions it has 8 components: 1
// scalar, 6 bivector and 1 quadvector. The quadvector part is not zero when
// the body turns in two planes at the same time. Do not take a quaternion
// class and add components to it. See ND-PHYSICS.md, A1.
//
// A rotor turns a vector or a blade with the sandwich product `x' = R x R~`.
// A unit rotor has `R R~ = 1`, thus the reverse is the inverse. Rounding
// makes a rotor lose its unit length. `rotorDefect` measures that loss, and
// `rotorCorrect` repairs it. See ND-PHYSICS.md, B2.
var rotor_exports = {};
__export(rotor_exports, {
rotorAddScaled: () => rotorAddScaled,
rotorApplyBivector: () => rotorApplyBivector,
rotorApplyVector: () => rotorApplyVector,
rotorApplyVectorInverse: () => rotorApplyVectorInverse,
rotorBetweenVectors: () => rotorBetweenVectors,
rotorBivectorMatrix: () => rotorBivectorMatrix,
rotorCorrect: () => rotorCorrect,
rotorDefect: () => rotorDefect,
rotorExp: () => rotorExp,
rotorFromBivectorAngle: () => rotorFromBivectorAngle,
rotorFromPlane: () => rotorFromPlane,
rotorIdentity: () => rotorIdentity,
rotorMatrix: () => rotorMatrix,
rotorMul: () => rotorMul,
rotorNorm: () => rotorNorm,
rotorReverse: () => rotorReverse,
rotorScale: () => rotorScale
});
/**
* A length below this one counts as zero. This is not a tolerance of the
* world, thus it is not in `defaultParams`: it says where the plane of two
* vectors stops to have a meaning, and it comes from the accuracy of the
* double and not from a choice of the user. See design rule 2.
*/
var ROTOR_ZERO = 1e-12;
/** The rotor that turns nothing. Its scalar component is 1. */
function rotorIdentity(D, out) {
const R = out || new Float64Array(D.r);
R.fill(0);
R[D.scalarSlot] = 1;
return R;
}
/**
* The geometric product `A B` of two rotors. The result is the rotor that
* puts `B` first and then `A`.
*
* This uses the small `r` by `r` table `D.evenGpSlot`, and not the full `N`
* by `N` table. Thus it does not build a multivector.
*
* @param {Float64Array} [out] a buffer of `r`. It must not be `A` or `B`.
* @throws {Error} when `out` is one of the inputs
*/
function rotorMul(D, A, B, out) {
const r = D.r;
const C = out || new Float64Array(r);
if (C === A || C === B) throw new Error("rotorMul: the output must not be an input");
C.fill(0);
for (let a = 0; a < r; a += 1) {
const va = A[a];
if (va === 0) continue;
for (let b = 0; b < r; b += 1) {
const vb = B[b];
if (vb === 0) continue;
const idx = a * r + b;
C[D.evenGpSlot[idx]] += D.evenGpSign[idx] * va * vb;
}
}
return C;
}
/** The reverse `R~`. For a unit rotor this is the inverse, thus the turn back. */
function rotorReverse(D, R, out) {
const C = out || new Float64Array(D.r);
for (let s = 0; s < D.r; s += 1) C[s] = D.reverseSign[D.evenBlade[s]] * R[s];
return C;
}
/** The length of `R`. A rotor that turns a body has the length 1. */
function rotorNorm(D, R) {
let s = 0;
for (let i = 0; i < D.r; i += 1) s += R[i] * R[i];
return Math.sqrt(s);
}
/** Multiplies each component of `R` by `f`. It gives a new rotor. */
function rotorScale(D, R, f, out) {
const C = out || new Float64Array(D.r);
for (let i = 0; i < D.r; i += 1) C[i] = R[i] * f;
return C;
}
/** Adds `f` times `S` to `R`, in place. It gives `R`. */
function rotorAddScaled(D, R, S, f) {
for (let i = 0; i < D.r; i += 1) R[i] += S[i] * f;
return R;
}
/**
* The rotor of a turn of `angle` radians in the plane of the axes `i` and
* `j`. The turn goes from the axis `i` to the axis `j`.
*
* The half angle is correct: the sandwich product applies the rotor two
* times, thus the body turns through the full angle.
*
* @param {number} i the first axis, 0 to `n - 1`
* @param {number} j the second axis. It must not be `i`.
* @param {number} angle the angle in radians
* @throws {Error} when `i` and `j` are the same axis
*/
function rotorFromPlane(D, i, j, angle, out) {
const R = rotorIdentity(D, out);
const p = D.biOfBlade[1 << i | 1 << j];
if (p < 0) throw new Error("rotorFromPlane: i and j must be different");
const sign = i < j ? 1 : -1;
R[D.scalarSlot] = Math.cos(angle / 2);
R[D.biSlot[p]] = -sign * Math.sin(angle / 2);
return R;
}
/**
* The exponential `exp(B)` of a bivector. This is the general way to make a
* rotor from a plane and an angle. In 4 dimensions `B` can hold two planes
* at the same time, and one series solves both.
*
* The method is scale and square:
* 1. Halve `B` until its length is 0.25 or less.
* 2. Sum 16 terms of the Taylor series of the exponential.
* 3. Square the result one time for each halving.
* A small input keeps the series short and the error low.
*
* @param {Float64Array} B a bivector of length `k`
* @returns {Float64Array} the rotor, of length `r`
*/
function rotorExp(D, B, out) {
let mag = 0;
for (let p = 0; p < D.k; p += 1) mag += B[p] * B[p];
mag = Math.sqrt(mag);
let steps = 0;
let scale = 1;
while (mag * scale > 0.25) {
scale /= 2;
steps += 1;
}
const X = new Float64Array(D.r);
for (let p = 0; p < D.k; p += 1) X[D.biSlot[p]] = B[p] * scale;
let term = rotorIdentity(D);
let acc = rotorIdentity(D);
let tmp = new Float64Array(D.r);
for (let m = 1; m <= 16; m += 1) {
rotorMul(D, term, X, tmp);
for (let i = 0; i < D.r; i += 1) tmp[i] /= m;
const t = term;
term = tmp;
tmp = t;
for (let i = 0; i < D.r; i += 1) acc[i] += term[i];
}
for (let s = 0; s < steps; s += 1) {
const sq = rotorMul(D, acc, acc);
acc = sq;
}
const R = out || new Float64Array(D.r);
R.set(acc);
return R;
}
/**
* The rotor of a turn of `angle` radians in the plane of the bivector `B`.
* It makes `B` a unit bivector first, thus the length of `B` has no effect.
* It gives the identity when `B` is zero.
*
* `angle` is the turn of the BODY, as in `rotorFromPlane`. The exponent
* holds the half angle, because the sandwich product applies the rotor two
* times, and it holds the minus of `dR/dt = -(1/2) w R`. Thus
* `rotorFromBivectorAngle(D, e_i ^ e_j, angle)` and
* `rotorFromPlane(D, i, j, angle)` give the same rotor.
*/
function rotorFromBivectorAngle(D, B, angle, out) {
let mag = 0;
for (let p = 0; p < D.k; p += 1) mag += B[p] * B[p];
mag = Math.sqrt(mag);
if (mag < 1e-300) return rotorIdentity(D, out);
const S = new Float64Array(D.k);
for (let p = 0; p < D.k; p += 1) S[p] = -B[p] / mag * (angle / 2);
return rotorExp(D, S, out);
}
/** The scratch multivectors of each `D`, for the sandwich products. */
var scratch = /* @__PURE__ */ new WeakMap();
/** Four scratch multivectors of the algebra `D`. They keep the step free of garbage. */
function pad(D) {
let s = scratch.get(D);
if (!s) {
s = { a: mvZero(D), b: mvZero(D), c: mvZero(D), d: mvZero(D) };
scratch.set(D, s);
}
return s;