-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathMatrix3d.ts
More file actions
3003 lines (2994 loc) · 132 KB
/
Copy pathMatrix3d.ts
File metadata and controls
3003 lines (2994 loc) · 132 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module CartesianGeometry
*/
import { assert } from "@itwin/core-bentley";
import { AxisIndex, AxisOrder, BeJSONFunctions, Geometry, StandardViewIndex } from "../Geometry";
import { Point4d } from "../geometry4d/Point4d";
import { Angle } from "./Angle";
import { Point2d } from "./Point2dVector2d";
import { Point3d, Vector3d, XYZ } from "./Point3dVector3d";
import { Transform } from "./Transform";
import { Matrix3dProps, WritableXYAndZ, XAndY, XYAndZ } from "./XYZProps";
/* eslint-disable @itwin/prefer-get */
// cSpell:words XXYZ YXYZ ZXYZ SaeedTorabi arctan newcommand diagonalization
/**
* PackedMatrix3dOps contains static methods for matrix operations where the matrix is a Float64Array.
* * The Float64Array contains the matrix entries in row-major order
* @internal
* ```
* equation
* \newcommand[1]\mij{#1_{00}\ #1_{01}\ a_{02}}
* ```
*/
export class PackedMatrix3dOps {
/**
* Load 9 doubles into the packed format.
* @param dest destination, allocated by caller
* @param a00 row 0, column 0 entry
* @param a01 row 0, column 1 entry
* @param a02 row 0, column 2 entry
* @param a10 row 1, column 0 entry
* @param a11 row 1, column 1 entry
* @param a12 row 1, column 2 entry
* @param a20 row 2, column 0 entry
* @param a21 row 2, column 1 entry
* @param a22 row 2, column 2 entry
*/
public static loadMatrix(
dest: Float64Array,
a00: number, a01: number, a02: number,
a10: number, a11: number, a12: number,
a20: number, a21: number, a22: number,
) {
dest[0] = a00; dest[1] = a01; dest[2] = a02;
dest[3] = a10; dest[4] = a11; dest[5] = a12;
dest[6] = a20; dest[7] = a21; dest[8] = a22;
}
/**
* Multiply 3x3 matrix `a*b`, store in `result`.
* @param a left matrix in product. ASSUMED length 9.
* @param b right matrix in product. ASSUMED length 9.
* @param result optional destination array of length 9. If insufficient length, a new array is returned. May refer to same array as `a` or `b`.
* @return matrix product `a*b`
*/
public static multiplyMatrixMatrix(a: Float64Array, b: Float64Array, result?: Float64Array): Float64Array {
if (!result || result.length < 9)
result = new Float64Array(9);
PackedMatrix3dOps.loadMatrix(
result,
(a[0] * b[0] + a[1] * b[3] + a[2] * b[6]),
(a[0] * b[1] + a[1] * b[4] + a[2] * b[7]),
(a[0] * b[2] + a[1] * b[5] + a[2] * b[8]),
(a[3] * b[0] + a[4] * b[3] + a[5] * b[6]),
(a[3] * b[1] + a[4] * b[4] + a[5] * b[7]),
(a[3] * b[2] + a[4] * b[5] + a[5] * b[8]),
(a[6] * b[0] + a[7] * b[3] + a[8] * b[6]),
(a[6] * b[1] + a[7] * b[4] + a[8] * b[7]),
(a[6] * b[2] + a[7] * b[5] + a[8] * b[8]),
);
return result;
}
/**
* Multiply 3x3 matrix `a*bTranspose`, store in `result`.
* @param a left matrix in product. ASSUMED length 9.
* @param b transpose of right matrix in product. ASSUMED length 9.
* @param result optional destination array of length 9. If insufficient length, a new array is returned. May refer to same array as `a` or `b`.
* @return matrix product `a*b^T`
*/
public static multiplyMatrixMatrixTranspose(a: Float64Array, b: Float64Array, result?: Float64Array): Float64Array {
if (!result || result.length < 9)
result = new Float64Array(9);
PackedMatrix3dOps.loadMatrix(
result,
(a[0] * b[0] + a[1] * b[1] + a[2] * b[2]),
(a[0] * b[3] + a[1] * b[4] + a[2] * b[5]),
(a[0] * b[6] + a[1] * b[7] + a[2] * b[8]),
(a[3] * b[0] + a[4] * b[1] + a[5] * b[2]),
(a[3] * b[3] + a[4] * b[4] + a[5] * b[5]),
(a[3] * b[6] + a[4] * b[7] + a[5] * b[8]),
(a[6] * b[0] + a[7] * b[1] + a[8] * b[2]),
(a[6] * b[3] + a[7] * b[4] + a[8] * b[5]),
(a[6] * b[6] + a[7] * b[7] + a[8] * b[8]),
);
return result;
}
/**
* Multiply 3x3 matrix `aTranspose*b`, store in `result`.
* @param a transpose of left matrix in product. ASSUMED length 9.
* @param b right matrix in product. ASSUMED length 9.
* @param result optional destination array of length 9. If insufficient length, a new array is returned. May refer to same array as `a` or `b`.
* @return matrix product `a^T*b`
*/
public static multiplyMatrixTransposeMatrix(a: Float64Array, b: Float64Array, result?: Float64Array): Float64Array {
if (!result || result.length < 9)
result = new Float64Array(9);
PackedMatrix3dOps.loadMatrix(
result,
(a[0] * b[0] + a[3] * b[3] + a[6] * b[6]),
(a[0] * b[1] + a[3] * b[4] + a[6] * b[7]),
(a[0] * b[2] + a[3] * b[5] + a[6] * b[8]),
(a[1] * b[0] + a[4] * b[3] + a[7] * b[6]),
(a[1] * b[1] + a[4] * b[4] + a[7] * b[7]),
(a[1] * b[2] + a[4] * b[5] + a[7] * b[8]),
(a[2] * b[0] + a[5] * b[3] + a[8] * b[6]),
(a[2] * b[1] + a[5] * b[4] + a[8] * b[7]),
(a[2] * b[2] + a[5] * b[5] + a[8] * b[8]),
);
return result;
}
/** Transpose 3x3 matrix `a` in place */
public static transposeInPlace(a: Float64Array) {
let q = a[1]; a[1] = a[3]; a[3] = q;
q = a[2]; a[2] = a[6]; a[6] = q;
q = a[5]; a[5] = a[7]; a[7] = q;
}
/**
* Compute transpose of 3x3 matrix `a`, store in `dest`.
* @param a source matrix. ASSUMED length 9. Note that `a` is not changed unless also passed as `dest`, i.e., `copyTransposed(a,a)` transposes `a` in place.
* @param dest optional destination array of length 9. If insufficient length, a new array is returned. May refer to same array as `a`.
* @return matrix `a^T`
*/
public static copyTransposed(a: Float64Array, dest?: Float64Array): Float64Array {
if (dest === a) {
PackedMatrix3dOps.transposeInPlace(dest);
} else {
if (!dest || dest.length < 9)
dest = new Float64Array(9);
dest[0] = a[0]; dest[1] = a[3]; dest[2] = a[6];
dest[3] = a[1]; dest[4] = a[4]; dest[5] = a[7];
dest[6] = a[2]; dest[7] = a[5]; dest[8] = a[8];
}
return dest;
}
/** Copy matrix `a` entries into `dest` */
public static copy(a: Float64Array, dest: Float64Array): Float64Array {
if (dest !== a) {
dest[0] = a[0]; dest[1] = a[1]; dest[2] = a[2];
dest[3] = a[3]; dest[4] = a[4]; dest[5] = a[5];
dest[6] = a[6]; dest[7] = a[7]; dest[8] = a[8];
}
return dest;
}
}
/**
* A Matrix3d is tagged indicating one of the following states:
* * unknown: it is not know if the matrix is invertible.
* * inverseStored: the matrix has its inverse stored.
* * singular: the matrix is known to be singular.
* @public
*/
export enum InverseMatrixState {
/**
* The invertibility of the `coffs` array has not been determined.
* Any `inverseCoffs` contents are random.
*/
unknown,
/**
* An inverse was computed and stored as the `inverseCoffs`
*/
inverseStored,
/**
* The `coffs` array is known to be singular.
* Any `inverseCoffs` contents are random.
*/
singular,
}
/**
* A Matrix3d is a 3x3 matrix.
* * A very common use is to hold a rigid body rotation (which has no scaling or skew), but the 3x3 contents can
* also hold scaling and skewing.
* * The matrix with 2-dimensional layout (note: a 2d array can be shown by a matrix)
* ```
* equation
* \matrixXY{A}
* ```
* is stored as 9 numbers in "row-major" order in a `Float64Array`, viz
* ```
* equation
* \rowMajorMatrixXY{A}
* ```
* * If the matrix inverse is known it is stored in the inverseCoffs array.
* * The inverse status (`unknown`, `inverseStored`, `singular`) status is indicated by the `inverseState` property.
* * Construction methods that are able to trivially construct the inverse, store it immediately and note that in
* the inverseState.
* * Constructions (e.g. createRowValues) for which the inverse is not immediately known mark the inverseState as
* unknown.
* * Later queries for the inverse, trigger full computation if needed at that time.
* * Most matrix queries are present with both "column" and "row" variants.
* * Usage elsewhere in the library is typically "column" based. For example, in a Transform that carries a
* coordinate frame, the matrix columns are the unit vectors for the axes.
* @public
*/
export class Matrix3d implements BeJSONFunctions {
/** Control flag for whether this class uses cached inverse of matrices. */
public static useCachedInverse = true; // cached inverse can be suppressed for testing.
/** Total number of times a cached inverse was used to avoid recompute */
public static numUseCache = 0;
/** Total number of times a cached inverse was computed. */
public static numComputeCache = 0;
/**
* Matrix contents as a flat array of numbers in row-major order.
* ```
* equation
* \mxy{B}
* \mij{B}
* ```
* * DO NOT directly modify this array. It will destroy safety of the cached inverse state.
*/
public coffs: Float64Array;
/**
* Matrix inverse contents.
* ```
* equation
* \mxy{A}
* ```
* * DO NOT directly modify this array. It will destroy integrity of the cached inverse state.
*/
public inverseCoffs: Float64Array | undefined;
/** Indicates if inverse is unknown, available, or known singular */
public inverseState: InverseMatrixState;
/** The identity matrix */
private static _identity: Matrix3d;
/** temporary buffer to store a matrix as a Float64Array (array of 9 floats) */
private static _productBuffer = new Float64Array(9);
/** The identity Matrix3d. Value is frozen and cannot be modified. */
public static get identity(): Matrix3d {
if (undefined === this._identity) {
this._identity = Matrix3d.createIdentity();
this._identity.freeze();
}
return this._identity;
}
/** Freeze this Matrix3d. */
public freeze(): Readonly<this> {
this.computeCachedInverse(true);
/*
hm.. can't freeze the Float64Arrays..
Object.freeze(this.coffs);
if (this.inverseCoffs)
Object.freeze(this.inverseCoffs);
*/
return Object.freeze(this);
}
/**
* Constructor
* @param coffs optional coefficient array of length at least 9 (CAPTURED). If undefined or insufficient length, a new array is created.
*/
public constructor(coffs?: Float64Array) {
this.coffs = (coffs && coffs.length >= 9) ? coffs : new Float64Array(9);
this.inverseCoffs = undefined;
this.inverseState = InverseMatrixState.unknown;
}
/**
* Return a json object containing the 9 numeric entries as a single array in row major order,
* `[ [1, 2, 3],[ 4, 5, 6], [7, 8, 9] ]`
*/
public toJSON(): Matrix3dProps {
return [[this.coffs[0], this.coffs[1], this.coffs[2]],
[this.coffs[3], this.coffs[4], this.coffs[5]],
[this.coffs[6], this.coffs[7], this.coffs[8]]];
}
/**
* Copy data from various input forms to this matrix.
* The source can be:
* * Another `Matrix3d`
* * An array of 3 arrays, each of which has the 3 numbers for a row of the matrix.
* * An array of 4 or 9 numbers in row major order.
* * **WARNING:** if json is an array of numbers but size is not 4 or 9, the matrix is set to zeros.
*/
public setFromJSON(json?: Matrix3dProps | Matrix3d): void {
this.inverseCoffs = undefined;
// if no json is passed
if (!json) {
this.setRowValues(0, 0, 0, 0, 0, 0, 0, 0, 0);
return;
}
// if json is Matrix3d
if (!Array.isArray(json)) {
if (json instanceof Matrix3d)
this.setFrom(json);
return;
}
// if json is Matrix3dProps and is an array of arrays
if (Geometry.isArrayOfNumberArray(json, 3, 3)) {
this.setRowValues(
json[0][0], json[0][1], json[0][2],
json[1][0], json[1][1], json[1][2],
json[2][0], json[2][1], json[2][2]);
return;
}
// if json is Matrix3dProps and is an array of numbers
if (json.length === 9) {
this.setRowValues(
json[0], json[1], json[2],
json[3], json[4], json[5],
json[6], json[7], json[8]);
return;
} else if (json.length === 4) {
this.setRowValues(
json[0], json[1], 0,
json[2], json[3], 0,
0, 0, 1);
return;
}
// if json is Matrix3dProps but is not the right size
this.setRowValues(0, 0, 0, 0, 0, 0, 0, 0, 0);
return;
}
/** Return a new Matrix3d constructed from contents of the json value. See `setFromJSON` for layout rules */
public static fromJSON(json?: Matrix3dProps): Matrix3d {
const result = Matrix3d.createIdentity();
result.setFromJSON(json);
return result;
}
/**
* Test if `this` and `other` are within tolerance in all numeric entries.
* @param tol optional tolerance for comparisons by Geometry.isDistanceWithinTol
*/
public isAlmostEqual(other: Matrix3d, tol?: number): boolean {
return Geometry.isDistanceWithinTol(this.maxDiff(other), tol);
}
/**
* Test if `this` and `other` are within tolerance in the column entries specified by `columnIndex`.
* @param tol optional tolerance for comparisons by Geometry.isDistanceWithinTol
*/
public isAlmostEqualColumn(columnIndex: AxisIndex, other: Matrix3d, tol?: number): boolean {
const max = Geometry.maxAbsXYZ(
this.coffs[columnIndex] - other.coffs[columnIndex],
this.coffs[columnIndex + 3] - other.coffs[columnIndex + 3],
this.coffs[columnIndex + 6] - other.coffs[columnIndex + 6]);
return Geometry.isDistanceWithinTol(max, tol);
}
/**
* Test if column (specified by `columnIndex`) entries of `this` and [ax,ay,az] are within tolerance.
* @param tol optional tolerance for comparisons by Geometry.isDistanceWithinTol
*/
public isAlmostEqualColumnXYZ(columnIndex: AxisIndex, ax: number, ay: number, az: number, tol?: number): boolean {
const max = Geometry.maxAbsXYZ(
this.coffs[columnIndex] - ax,
this.coffs[columnIndex + 3] - ay,
this.coffs[columnIndex + 6] - az);
return Geometry.isDistanceWithinTol(max, tol);
}
/**
* A matrix equivalence test, returning true if and only if the matrices are almost equal,
* or all of the following column comparisons hold:
* * z columns are almost equal, and
* * x columns differ only by a rotation of angle t around the z column, and
* * y columns differ only by a rotation of the same angle t around the z column.
* @param other matrix to compare
* @param tol optional distance tolerance, for comparisons by Geometry.isDistanceWithinTol
* @return whether matrices are almost equal modulo a rotation around their common nonzero z-column.
*/
public isAlmostEqualAllowZRotation(other: Matrix3d, tol?: number): boolean {
if (this.isAlmostEqual(other, tol))
return true;
if (!this.isAlmostEqualColumn(AxisIndex.Z, other, tol))
return false;
const columnX = this.columnX();
const columnY = this.columnY();
const columnZ = this.columnZ();
const toOtherColumnX = columnX.signedAngleTo(other.columnX(), columnZ);
let testColumn = Vector3d.createRotateVectorAroundVector(columnX, columnZ, toOtherColumnX);
if (!testColumn)
return false; // columnZ is zero length
if (!other.isAlmostEqualColumnXYZ(0, testColumn.x, testColumn.y, testColumn.z, tol))
return false; // columnX rotated around columnZ by angle doesn't end up at other.columnX
testColumn = Vector3d.createRotateVectorAroundVector(columnY, columnZ, toOtherColumnX);
if (!testColumn)
return false;
if (!other.isAlmostEqualColumnXYZ(1, testColumn.x, testColumn.y, testColumn.z, tol))
return false; // columnY rotated around columnZ by angle doesn't end up at other.columnY
return true;
}
/** Test for exact (bitwise) equality with other. */
public isExactEqual(other: Matrix3d): boolean {
return this.maxDiff(other) === 0.0;
}
/** test if all entries in the z row and column are exact 001, i.e. the matrix only acts in 2d */
public get isXY(): boolean {
return this.coffs[2] === 0.0
&& this.coffs[5] === 0.0
&& this.coffs[6] === 0.0
&& this.coffs[7] === 0.0
&& this.coffs[8] === 1.0;
}
/**
* If result is not provided, then the method returns a new (zeroed) matrix; otherwise the result is
* not zeroed first and is just returned as-is.
*/
private static _create(result?: Matrix3d): Matrix3d {
return result ? result : new Matrix3d();
}
/**
* Returns a Matrix3d populated by numeric values given in row-major order.
* Sets all entries in the matrix from call parameters appearing in row-major order, i.e.
* ```
* equation
* \begin{bmatrix}a_{xx}\ a_{xy}\ a_{xz}\\ a_{yx}\ a_{yy}\ a_{yz}\\ a_{zx}\ a_{zy}\ a_{zz}\end{bmatrix}
* ```
* @param axx Row x, column x(0, 0) entry
* @param axy Row x, column y(0, 1) entry
* @param axz Row x, column z(0, 2) entry
* @param ayx Row y, column x(1, 0) entry
* @param ayy Row y, column y(1, 1) entry
* @param ayz Row y, column z(1, 2) entry
* @param azx Row z, column x(2, 0) entry
* @param azy Row z, column y(2, 2) entry
* @param azz row z, column z(2, 3) entry
*/
public static createRowValues(
axx: number, axy: number, axz: number,
ayx: number, ayy: number, ayz: number,
azx: number, azy: number, azz: number,
result?: Matrix3d,
): Matrix3d {
result = result ? result : new Matrix3d();
result.inverseState = InverseMatrixState.unknown;
result.coffs[0] = axx; result.coffs[1] = axy; result.coffs[2] = axz;
result.coffs[3] = ayx; result.coffs[4] = ayy; result.coffs[5] = ayz;
result.coffs[6] = azx; result.coffs[7] = azy; result.coffs[8] = azz;
return result;
}
/**
* Create a Matrix3d with caller-supplied coefficients and optional inverse coefficients.
* * The inputs are captured into (i.e., owned by) the new Matrix3d.
* * The caller is responsible for validity of the inverse coefficients.
* * If either array is insufficiently sized, it is ignored.
* @param coffs (required) array of 9 coefficients.
* @param inverseCoffs (optional) array of 9 coefficients.
* @returns a Matrix3d populated by a coffs array.
*/
public static createCapture(coffs: Float64Array, inverseCoffs?: Float64Array): Matrix3d {
const result = new Matrix3d(coffs);
if (inverseCoffs && inverseCoffs.length >= 9) {
result.inverseCoffs = inverseCoffs;
result.inverseState = InverseMatrixState.inverseStored;
} else {
result.inverseState = InverseMatrixState.unknown;
}
return result;
}
/**
* Create a matrix by distributing vectors to columns in one of 6 orders.
* @param axisOrder identifies where the columns are placed.
* @param columnA vector to place in the column specified by first letter in the AxisOrder name.
* @param columnB vector to place in the column specified by second letter in the AxisOrder name.
* @param columnC vector to place in the column specified by third letter in the AxisOrder name.
* @param result optional result matrix3d
* * Example: If you pass AxisOrder.YZX, then result will be [columnC, columnA, columnB] because
* first letter Y means columnA should go to the second column, second letter Z means columnB should
* go to the third column, and third letter X means columnC should go to the first column.
*/
public static createColumnsInAxisOrder(
axisOrder: AxisOrder, columnA: Vector3d | undefined, columnB: Vector3d | undefined,
columnC: Vector3d | undefined, result?: Matrix3d,
): Matrix3d {
if (!result) result = new Matrix3d();
if (axisOrder === AxisOrder.YZX) {
result.setColumns(columnC, columnA, columnB);
} else if (axisOrder === AxisOrder.ZXY) {
result.setColumns(columnB, columnC, columnA);
} else if (axisOrder === AxisOrder.XZY) {
result.setColumns(columnA, columnC, columnB);
} else if (axisOrder === AxisOrder.YXZ) {
result.setColumns(columnB, columnA, columnC);
} else if (axisOrder === AxisOrder.ZYX) {
result.setColumns(columnC, columnB, columnA);
} else { // AxisOrder.XYZ
result.setColumns(columnA, columnB, columnC);
}
return result;
}
/**
* Create the inverseCoffs member (filled with zeros)
* This is for use by matrix * matrix multiplications which need to be sure the member is there to be
* filled with method-specific content.
*/
private createInverseCoffsWithZeros(): this is { inverseCoffs: Float64Array } {
if (!this.inverseCoffs) {
this.inverseState = InverseMatrixState.unknown;
this.inverseCoffs = new Float64Array(9);
}
return this.inverseCoffs !== undefined;
}
/**
* Copy the transpose of the coffs to the inverseCoffs.
* * Mark the matrix as inverseStored.
*/
private setupInverseTranspose() {
const coffs = this.coffs;
this.inverseState = InverseMatrixState.inverseStored;
this.inverseCoffs = Float64Array.from([
coffs[0], coffs[3], coffs[6],
coffs[1], coffs[4], coffs[7],
coffs[2], coffs[5], coffs[8],
]);
}
/**
* Set all entries in the matrix from call parameters appearing in row-major order.
* @param axx Row x, column x (0,0) entry
* @param axy Row x, column y (0,1) entry
* @param axz Row x, column z (0,2) entry
* @param ayx Row y, column x (1,0) entry
* @param ayy Row y, column y (1,1) entry
* @param ayz Row y, column z (1,2) entry
* @param azx Row z, column x (2,0) entry
* @param azy Row z, column y (2,2) entry
* @param azz row z, column z (2,3) entry
*/
public setRowValues(
axx: number, axy: number, axz: number,
ayx: number, ayy: number, ayz: number,
azx: number, azy: number, azz: number): void {
this.coffs[0] = axx; this.coffs[1] = axy; this.coffs[2] = axz;
this.coffs[3] = ayx; this.coffs[4] = ayy; this.coffs[5] = ayz;
this.coffs[6] = azx; this.coffs[7] = azy; this.coffs[8] = azz;
this.inverseState = InverseMatrixState.unknown;
}
/** Set the matrix to an identity. */
public setIdentity() {
this.setRowValues(1, 0, 0, 0, 1, 0, 0, 0, 1);
this.setupInverseTranspose();
}
/** Set the matrix to all zeros. */
public setZero() {
this.setRowValues(0, 0, 0, 0, 0, 0, 0, 0, 0);
this.inverseState = InverseMatrixState.singular;
}
/** Copy contents from the `other` matrix. If `other` is undefined, use identity matrix. */
public setFrom(other: Matrix3d | undefined): void {
if (other === undefined) {
this.setIdentity();
return;
}
if (other !== this) {
for (let i = 0; i < 9; i++)
this.coffs[i] = other.coffs[i];
if (other.inverseState === InverseMatrixState.inverseStored && other.inverseCoffs !== undefined) {
if (this.createInverseCoffsWithZeros()) {
for (let i = 0; i < 9; i++)
this.inverseCoffs[i] = other.inverseCoffs[i];
this.inverseState = InverseMatrixState.inverseStored;
}
} else if (other.inverseState !== InverseMatrixState.inverseStored) {
this.inverseState = other.inverseState;
} else { // This is reached when other says stored but does not have coffs. This should not happen.
this.inverseState = InverseMatrixState.unknown;
}
}
}
/**
* Return a clone of this matrix.
* * Coefficients are copied.
* * Inverse coefficients and inverse status are copied if stored by `this`.
*/
public clone(result?: Matrix3d): Matrix3d {
result = result ? result : new Matrix3d();
result.setFrom(this);
return result;
}
/**
* Create a matrix with all zeros.
* * Note that for geometry transformations "all zeros" is not a useful default state.
* * Hence, almost always use `createIdentity` for graphics transformations.
* * "All zeros" is appropriate for summing moment data.
* ```
* equation
* \begin{bmatrix}0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0\end{bmatrix}
* ```
*/
public static createZero(): Matrix3d {
const retVal = new Matrix3d();
retVal.inverseState = InverseMatrixState.singular;
return retVal;
}
/**
* Create an identity matrix.
* * All diagonal entries (xx,yy,zz) are one
* * All others are zero.
* * This (rather than "all zeros") is the useful state for most graphics transformations.
* ```
* equation
* \begin{bmatrix}1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1\end{bmatrix}
* ```
*
*/
public static createIdentity(result?: Matrix3d): Matrix3d {
result = result ? result : new Matrix3d();
result.setIdentity();
return result;
}
/**
* Create a matrix with distinct x,y,z diagonal (scale) entries.
* ```
* equation
* \begin{bmatrix}s_x & 0 & 0 \\ 0 & s_y & 0\\ 0 & 0 & s_z\end{bmatrix}
* ```
*/
public static createScale(
scaleFactorX: number, scaleFactorY: number, scaleFactorZ: number, result?: Matrix3d,
): Matrix3d {
if (result)
result.setZero();
else
result = new Matrix3d();
result.coffs[0] = scaleFactorX;
result.coffs[4] = scaleFactorY;
result.coffs[8] = scaleFactorZ;
if (scaleFactorX === 0 || scaleFactorY === 0 || scaleFactorZ === 0) {
result.inverseState = InverseMatrixState.singular;
} else {
result.inverseState = InverseMatrixState.inverseStored;
result.inverseCoffs = Float64Array.from(
[1 / scaleFactorX, 0, 0,
0, 1 / scaleFactorY, 0,
0, 0, 1 / scaleFactorZ],
);
}
return result;
}
/**
* Create a matrix with uniform scale factor "s":
* ```
* equation
* \begin{bmatrix}s & 0 & 0 \\ 0 & s & 0\\ 0 & 0 & s\end{bmatrix}
* ```
*/
public static createUniformScale(scaleFactor: number): Matrix3d {
return Matrix3d.createScale(scaleFactor, scaleFactor, scaleFactor);
}
/**
* Return a vector that is perpendicular to the input `vectorA`.
* * Among the infinite number of perpendiculars possible, this method favors having one in the xy plane.
* * Hence, when `vectorA` is close to the Z axis, the returned vector is `vectorA cross -unitY`
* but when `vectorA` is NOT close to the Z axis, the returned vector is `unitZ cross vectorA`.
*/
public static createPerpendicularVectorFavorXYPlane(vectorA: Vector3d, result?: Vector3d): Vector3d {
const a = vectorA.magnitude();
const scale = 64.0; // A constant from the dawn of time in the CAD industry
const b = a / scale;
// if vectorA is close to the Z axis
if (Math.abs(vectorA.x) < b && Math.abs(vectorA.y) < b) {
return Vector3d.createCrossProduct(vectorA.x, vectorA.y, vectorA.z, 0, -1, 0, result);
}
// if vectorA is NOT close to the Z axis
return Vector3d.createCrossProduct(0, 0, 1, vectorA.x, vectorA.y, vectorA.z, result);
}
/**
* Return a vector that is perpendicular to the input `vectorA`.
* * Among the infinite number of perpendiculars possible, this method favors having one near the plane
* containing Z.
* That is achieved by cross product of `this` vector with the result of createPerpendicularVectorFavorXYPlane.
*/
public static createPerpendicularVectorFavorPlaneContainingZ(vectorA: Vector3d, result?: Vector3d): Vector3d {
/**
* vectorA, result (below), and "vectorA cross result" form a coordinate system where "result" is located on
* the XY-plane. Once you've got a coordinate system with an axis in the XY-plane, your other two axes form
* a plane that includes the z-axis.
*/
result = Matrix3d.createPerpendicularVectorFavorXYPlane(vectorA, result);
return vectorA.crossProduct(result, result);
}
/**
* Create a matrix from column vectors, shuffled into place per axisOrder
* * For example, if axisOrder = XYZ then it returns [vectorU, vectorV, vectorW]
* * Another example, if axisOrder = YZX then it returns [vectorW, vectorU, vectorV] because
* Y is at index 0 so vectorU goes to the column Y (column 2), Z is at index 1 so vectorV goes
* to the column Z (column 3), and X is at index 2 so vectorW goes to the column X (column 1)
*/
public static createShuffledColumns(
vectorU: Vector3d, vectorV: Vector3d, vectorW: Vector3d, axisOrder: AxisOrder, result?: Matrix3d,
): Matrix3d {
const target = Matrix3d._create(result);
target.setColumn(Geometry.axisOrderToAxis(axisOrder, 0), vectorU);
target.setColumn(Geometry.axisOrderToAxis(axisOrder, 1), vectorV);
target.setColumn(Geometry.axisOrderToAxis(axisOrder, 2), vectorW);
target.inverseState = InverseMatrixState.unknown;
return target;
}
/**
* Create a new orthogonal matrix (perpendicular columns, unit length, transpose is inverse).
* * `vectorA1 = Normalized vectorA` is placed in the column specified by the **first** letter in
* the AxisOrder name.
* * Normalized `vectorC1 = vectorA1 cross vectorB` is placed in the column specified by the **third**
* letter in the AxisOrder name.
* * Normalized `vectorC1 cross vectorA` is placed in the column specified by the **second**
* letter in the AxisOrder name.
* * This function internally uses [[createShuffledColumns]].
*/
public static createRigidFromColumns(
vectorA: Vector3d, vectorB: Vector3d, axisOrder: AxisOrder, result?: Matrix3d,
): Matrix3d | undefined {
const vectorA1 = vectorA.normalize();
if (vectorA1) {
const vectorC1 = vectorA1.unitCrossProduct(vectorB);
if (vectorC1) {
const vectorB1 = vectorC1.unitCrossProduct(vectorA);
if (vectorB1) {
const retVal = Matrix3d.createShuffledColumns(vectorA1, vectorB1, vectorC1, axisOrder, result);
retVal.setupInverseTranspose();
return retVal;
}
}
}
return undefined;
}
/**
* Construct a rigid matrix (orthogonal matrix with determinant 1) using vectorA and its 2 perpendiculars.
* * If axisOrder is not passed then `AxisOrder = AxisOrder.ZXY` is used as default.
* * This function internally uses createPerpendicularVectorFavorXYPlane and createRigidFromColumns.
* * Passing the normal of a plane P into this method returns a matrix whose transpose rotates geometry in P
* to the xy-plane if P contains the origin, or to a plane parallel to the xy-plane if P does not contain the origin.
* * Visualization can be found at https://www.itwinjs.org/sandbox/SaeedTorabi/2PerpendicularVectorsTo1Vector
*/
public static createRigidHeadsUp(
vectorA: Vector3d, axisOrder: AxisOrder = AxisOrder.ZXY, result?: Matrix3d,
): Matrix3d {
const vectorB = Matrix3d.createPerpendicularVectorFavorXYPlane(vectorA);
const matrix = Matrix3d.createRigidFromColumns(vectorA, vectorB, axisOrder, result);
if (matrix) {
matrix.setupInverseTranspose();
return matrix;
}
return Matrix3d.createIdentity(result);
}
/**
* Return the matrix for rotation of `angle` around desired `axis`
* * Visualization can be found at https://www.itwinjs.org/sandbox/SaeedTorabi/CubeTransform
* @param axis the axis of rotation
* @param angle the angle of rotation
* @param result caller-allocated matrix (optional)
* @returns the `rotation matrix` or `undefined` (if axis magnitude is near zero).
*/
public static createRotationAroundVector(axis: Vector3d, angle: Angle, result?: Matrix3d): Matrix3d | undefined {
// Rodriguez formula (matrix form), https://mathworld.wolfram.com/RodriguesRotationFormula.html
const c = angle.cos();
const s = angle.sin();
const v = 1.0 - c;
const unit = axis.normalize();
if (unit) {
const retVal = Matrix3d.createRowValues(
unit.x * unit.x * v + c, unit.x * unit.y * v - s * unit.z, unit.x * unit.z * v + s * unit.y,
unit.y * unit.x * v + s * unit.z, unit.y * unit.y * v + c, unit.y * unit.z * v - s * unit.x,
unit.z * unit.x * v - s * unit.y, unit.z * unit.y * v + s * unit.x, unit.z * unit.z * v + c,
result,
);
retVal.setupInverseTranspose();
return retVal;
}
return undefined;
}
/** Returns a rotation of specified angle around one of the main axis (X,Y,Z).
* @param axisIndex index of axis (AxisIndex.X, AxisIndex.Y, AxisIndex.Z) kept fixed by the rotation.
* @param angle angle of rotation
* @param result optional result matrix.
* * Math details of 3d rotation matrices derivation can be found at docs/learning/geometry/Angle.md
*/
public static createRotationAroundAxisIndex(axisIndex: AxisIndex, angle: Angle, result?: Matrix3d): Matrix3d {
const c = angle.cos();
const s = angle.sin();
let myResult;
if (axisIndex === AxisIndex.X) {
myResult = Matrix3d.createRowValues(
1, 0, 0,
0, c, -s,
0, s, c,
result);
} else if (axisIndex === AxisIndex.Y) {
myResult = Matrix3d.createRowValues(
c, 0, s,
0, 1, 0,
-s, 0, c,
result);
} else {
myResult = Matrix3d.createRowValues(
c, -s, 0,
s, c, 0,
0, 0, 1,
result);
}
myResult.setupInverseTranspose();
return myResult;
}
/**
* Replace current rows Ui and Uj with (c*Ui + s*Uj) and (c*Uj - s*Ui).
* * There is no checking for i,j being 0,1,2.
* * The instance matrix A is multiplied in place on the left by a Givens rotation G, resulting in the matrix G*A.
* @param i first row index. **must be 0,1,2** (unchecked)
* @param j second row index. **must be 0,1,2** (unchecked)
* @param c fist coefficient
* @param s second coefficient
*/
private applyGivensRowOp(i: number, j: number, c: number, s: number): void {
let ii = 3 * i;
let jj = 3 * j;
const limit = ii + 3;
for (; ii < limit; ii++, jj++) {
const a = this.coffs[ii];
const b = this.coffs[jj];
this.coffs[ii] = a * c + b * s;
this.coffs[jj] = -a * s + b * c;
}
}
/**
* Replace current columns Ui and Uj with (c*Ui + s*Uj) and (c*Uj - s*Ui).
* * There is no checking for i,j being 0,1,2.
* * The instance matrix A is multiplied in place on the right by a Givens rotation G, resulting in the matrix A*G.
* * This is used in compute intensive inner loops
* @param i first row index. **must be 0,1,2** (unchecked)
* @param j second row index. **must be 0,1,2** (unchecked)
* @param c fist coefficient
* @param s second coefficient
*/
public applyGivensColumnOp(i: number, j: number, c: number, s: number): void {
const limit = i + 9;
for (; i < limit; i += 3, j += 3) {
const a = this.coffs[i];
const b = this.coffs[j];
this.coffs[i] = a * c + b * s;
this.coffs[j] = -a * s + b * c;
}
}
/**
* Create a matrix from column vectors.
* ```
* equation
* \begin{bmatrix}U_x & V_x & W_x \\ U_y & V_y & W_y \\ U_z & V_z & W_z \end{bmatrix}
* ```
*/
public static createColumns(vectorU: Vector3d, vectorV: Vector3d, vectorW: Vector3d, result?: Matrix3d): Matrix3d {
return Matrix3d.createRowValues
(
vectorU.x, vectorV.x, vectorW.x,
vectorU.y, vectorV.y, vectorW.y,
vectorU.z, vectorV.z, vectorW.z,
result,
);
}
/**
* Create a matrix with each column's _x,y_ parts given `XAndY` and separate numeric z values.
* ```
* equation
* \begin{bmatrix}U_x & V_x & W_x \\ U_y & V_y & W_y \\ u & v & w \end{bmatrix}
* ```
*/
public static createColumnsXYW(
vectorU: XAndY, u: number,
vectorV: XAndY, v: number,
vectorW: XAndY, w: number,
result?: Matrix3d,
): Matrix3d {
return Matrix3d.createRowValues
(
vectorU.x, vectorV.x, vectorW.x,
vectorU.y, vectorV.y, vectorW.y,
u, v, w,
result,
);
}
/**
* Create a matrix from "as viewed" right and up vectors.
* * ColumnX points in the rightVector direction.
* * ColumnY points in the upVector direction.
* * ColumnZ is a unit cross product of ColumnX and ColumnY.
* * Optionally rotate by 45 degrees around `upVector` to bring its left or right vertical edge to center.
* * Optionally rotate by arctan(1/sqrt(2)) ~ 35.264 degrees around `rightVector` to bring the top or bottom
* horizontal edge of the view to the center (for isometric views).
*
* This is expected to be used with various principal unit vectors that are perpendicular to each other.
* * STANDARD TOP VIEW: createViewedAxes(Vector3d.unitX(), Vector3d.unitY(), 0, 0)
* * STANDARD FRONT VIEW: createViewedAxes(Vector3d.unitX(), Vector3d.unitZ(), 0, 0)
* * STANDARD BACK VIEW: createViewedAxes(Vector3d.unitX(-1), Vector3d.unitZ(), 0, 0)
* * STANDARD RIGHT VIEW: createViewedAxes(Vector3d.unitY(), Vector3d.unitZ(), 0, 0)
* * STANDARD LEFT VIEW: createViewedAxes(Vector3d.unitY(-1), Vector3d.unitZ(), 0, 0)
* * STANDARD BOTTOM VIEW: createViewedAxes(Vector3d.unitX(), Vector3d.unitY(-1), 0, 0)
* * STANDARD ISO VIEW: createViewedAxes(Vector3d.unitX(), Vector3d.unitZ(), -1, 1)
* * STANDARD RIGHT ISO VIEW: createViewedAxes(Vector3d.unitX(), Vector3d.unitZ(), 1, 1)
* * Front, right, back, left, top, and bottom standard views are views from faces of the cube
* and iso and right iso standard views are views from corners of the cube.
* * Note: createViewedAxes is column-based so always returns local to world
*
* @param rightVector ColumnX of the returned matrix. Expected to be perpendicular to upVector.
* @param upVector ColumnY of the returned matrix. Expected to be perpendicular to rightVector.
* @param leftNoneRight Specifies the ccw rotation around `upVector` axis. Normally one of "-1", "0", and "1",
* where "-1" indicates rotation by 45 degrees to bring the left vertical edge to center, "0" means no rotation,
* and "1" indicates rotation by 45 degrees to bring the right vertical edge to center. Other numbers are
* used as multiplier for this 45 degree rotation.
* @param topNoneBottom Specifies the ccw rotation around `rightVector` axis. Normally one of "-1", "0", and "1",
* where "-1" indicates isometric rotation (35.264 degrees) to bring the bottom upward, "0" means no rotation,
* and "1" indicates isometric rotation (35.264 degrees) to bring the top downward. Other numbers are
* used as multiplier for the 35.264 degree rotation.
* @returns matrix = [rightVector, upVector, rightVector cross upVector] with the applied rotations specified
* by leftNoneRight and topNoneBottom. Returns undefined if rightVector and upVector are parallel.
*/
public static createViewedAxes(
rightVector: Vector3d, upVector: Vector3d, leftNoneRight: number = 0, topNoneBottom: number = 0,
): Matrix3d | undefined {
const columnZ = rightVector.crossProduct(upVector);
if (columnZ.normalizeInPlace()) {
// matrix = [rightVector, upVector, rightVector cross upVector]
const matrix = Matrix3d.createColumns(rightVector, upVector, columnZ);
// "45 degrees * leftNoneRight" rotation around Y
if (leftNoneRight !== 0.0) {
let c = Math.sqrt(0.5);
let s = leftNoneRight < 0.0 ? -c : c;
if (Math.abs(leftNoneRight) !== 1.0) {
const radians = Angle.degreesToRadians(45.0 * leftNoneRight);
c = Math.cos(radians);
s = Math.sin(radians);
}
matrix.applyGivensColumnOp(2, 0, c, s); // rotate around Y (equivalent to matrix*rotationY)
}
// "35.264 degrees * topNoneBottom" rotation around X
if (topNoneBottom !== 0.0) {
const theta = topNoneBottom * Math.atan(Math.sqrt(0.5));
const c = Math.cos(theta);
const s = Math.sin(theta);
matrix.applyGivensColumnOp(1, 2, c, -s); // rotate around X (equivalent to matrix*rotationX)
}
return matrix;
}
return undefined;
}
/**
* Create a rotation matrix for one of the 8 standard views.
* * Default is TOP view (`local X = world X`, `local Y = world Y`, `local Z = world Z`).
* * To change view from the TOP to one of the other 7 standard views, we need to multiply "world data" to
* the corresponding matrix1 provided by `createStandardWorldToView(index, false)` and then
* `matrix1.multiply(world data)` will return "local data".
* * To change view back to the TOP, we need to multiply "local data" to the corresponding matrix2 provided
* by `createStandardWorldToView(index, true)` and then `matrix2.multiply(local data)` will returns "world data".
* * Note: No matter how you rotate the world axis, local X is always pointing right, local Y is always pointing up,
* and local Z is always pointing toward you.
*
* @param index standard view index `StandardViewIndex.Top, Bottom, Left, Right, Front, Back, Iso, RightIso`
* @param invert if false (default), the return matrix is world to local (view) and if true, the the return
* matrix is local (view) to world.
* @param result optional result.
*/
public static createStandardWorldToView(
index: StandardViewIndex, invert: boolean = false, result?: Matrix3d,
): Matrix3d {
switch (index) {
// Start with TOP view, ccw rotation by 180 degrees around X
case StandardViewIndex.Bottom:
result = Matrix3d.createRowValues(
1, 0, 0,
0, -1, 0,
0, 0, -1,
);
break;
// Start with TOP view, ccw rotation by -90 degrees around X and by 90 degrees around Z
case StandardViewIndex.Left:
result = Matrix3d.createRowValues(
0, -1, 0,
0, 0, 1,
-1, 0, 0,
);
break;
// Start with TOP view, ccw rotation by -90 degrees around X and by -90 degrees around Z
case StandardViewIndex.Right:
result = Matrix3d.createRowValues(
0, 1, 0,
0, 0, 1,
1, 0, 0,
);
break;
// Start with TOP view, ccw rotation by -90 degrees around X
case StandardViewIndex.Front:
result = Matrix3d.createRowValues(
1, 0, 0,
0, 0, 1,
0, -1, 0,
);
break;
// Start with TOP view, ccw rotation by -90 degrees around X and by 180 degrees around Z
case StandardViewIndex.Back:
result = Matrix3d.createRowValues(
-1, 0, 0,
0, 0, 1,
0, 1, 0,