-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
5370 lines (4900 loc) · 180 KB
/
Copy pathapp.js
File metadata and controls
5370 lines (4900 loc) · 180 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
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { TransformControls } from "three/addons/controls/TransformControls.js";
import { OBJLoader } from "three/addons/loaders/OBJLoader.js";
import { PLYLoader } from "three/addons/loaders/PLYLoader.js";
import { STLLoader } from "three/addons/loaders/STLLoader.js";
import { ConvexHull } from "three/addons/math/ConvexHull.js";
import { OBJExporter } from "three/addons/exporters/OBJExporter.js";
import { PLYExporter } from "three/addons/exporters/PLYExporter.js";
import { STLExporter } from "three/addons/exporters/STLExporter.js";
const MODEL_SIZE = 2.7;
const MODEL_HALF_SIZE = MODEL_SIZE / 2;
const GRID_LIMIT = 12;
const MIN_MODEL_RADIUS = 0.35;
const GEOMETRY_EPSILON = 1e-8;
const MAX_OBB_CANDIDATE_FRAMES = 6000;
const PRINCIPAL_AXIS_SEPARATION_RATIO = 1.05;
const LOCAL_PLANE_MAX_NEIGHBORS = 320;
const LOCAL_PLANE_FIT_NEIGHBORS = 128;
const LOCAL_PLANE_RANSAC_NEIGHBORS = 28;
const SUPPORTED_EXTENSIONS = new Set(["obj", "ply", "stl"]);
const DEFAULT_VIEW_DIRECTION = new THREE.Vector3(0.55, 0.62, 0.56).normalize();
const PLANE_COLORS = [0x5a5a5a, 0x168aad, 0xe07a2f, 0x2f9d62, 0xd94f70, 0x4f83a8];
const ALIGNMENT_TARGETS = {
z: {
name: "Top (XY)",
origin: new THREE.Vector3(0, 0, 0),
normal: new THREE.Vector3(0, 0, 1),
xAxis: new THREE.Vector3(1, 0, 0),
},
y: {
name: "Front (XZ)",
origin: new THREE.Vector3(0, 0, 0),
normal: new THREE.Vector3(0, 1, 0),
xAxis: new THREE.Vector3(1, 0, 0),
},
x: {
name: "Right (YZ)",
origin: new THREE.Vector3(0, 0, 0),
normal: new THREE.Vector3(1, 0, 0),
xAxis: new THREE.Vector3(0, 1, 0),
},
};
const WORLD_REFERENCE_PLANES = [
{
id: "world-xy",
name: "Top (XY)",
method: "Origin plane",
origin: new THREE.Vector3(0, 0, 0),
normal: new THREE.Vector3(0, 0, 1),
xAxis: new THREE.Vector3(1, 0, 0),
space: "world",
builtIn: true,
},
{
id: "world-yz",
name: "Right (YZ)",
method: "Origin plane",
origin: new THREE.Vector3(0, 0, 0),
normal: new THREE.Vector3(1, 0, 0),
xAxis: new THREE.Vector3(0, 1, 0),
space: "world",
builtIn: true,
},
{
id: "world-xz",
name: "Front (XZ)",
method: "Origin plane",
origin: new THREE.Vector3(0, 0, 0),
normal: new THREE.Vector3(0, 1, 0),
xAxis: new THREE.Vector3(1, 0, 0),
space: "world",
builtIn: true,
},
];
const state = {
displayMode: "mesh",
modelCenterVisible: true,
originPlanes: {
top: true,
front: true,
right: true,
},
scaleLinked: true,
transformGizmo: {
mode: "translate",
space: "world",
gridSnap: false,
gridStep: 1,
angleSnap: false,
angleStep: 15,
},
model: {
position: { x: 0, y: 0, z: 0 },
rotation: { x: 0, y: 0, z: 0 },
scale: { x: 1, y: 1, z: 1 },
},
};
const canvas = document.querySelector("#viewportCanvas");
const workspace = document.querySelector(".workspace");
const dropOverlay = document.querySelector("#dropOverlay");
const toast = document.querySelector("#toast");
let toastTimer = 0;
function showToast(message) {
window.clearTimeout(toastTimer);
toast.textContent = message;
toast.classList.add("is-visible");
toastTimer = window.setTimeout(() => toast.classList.remove("is-visible"), 3200);
}
function setPressedState(buttons, activeButton) {
for (const button of buttons) {
const isActive = button === activeButton;
button.classList.toggle("is-active", isActive);
button.setAttribute("aria-pressed", String(isActive));
}
}
function getFileExtension(fileName) {
const separatorIndex = fileName.lastIndexOf(".");
return separatorIndex >= 0 ? fileName.slice(separatorIndex + 1).toLowerCase() : "";
}
function getDisplayName(fileName) {
const separatorIndex = fileName.lastIndexOf(".");
return separatorIndex > 0 ? fileName.slice(0, separatorIndex) : fileName;
}
function getPlyFileInfo(data) {
const headerByteLength = Math.min(data.byteLength, 1024 * 1024);
const header = new TextDecoder("ascii").decode(
new Uint8Array(data, 0, headerByteLength),
);
const headerEnd = header.indexOf("end_header");
if (headerEnd < 0) {
throw new Error("The selected PLY file has an invalid or oversized header.");
}
const faceElement = header.slice(0, headerEnd).match(/^element\s+face\s+(\d+)\s*$/im);
const format = header
.slice(0, headerEnd)
.match(/^format\s+(ascii|binary_little_endian|binary_big_endian)\s+1\.0\s*$/im);
if (!format) throw new Error("The selected PLY file uses an unsupported encoding.");
return {
encoding: format[1].toLowerCase(),
hasFaces: faceElement !== null && Number.parseInt(faceElement[1], 10) > 0,
};
}
function getStlEncoding(data) {
const bytes = new Uint8Array(data);
if (data.byteLength >= 84) {
const triangleCount = new DataView(data).getUint32(80, true);
if (84 + triangleCount * 50 === data.byteLength) return "binary";
}
const solid = [115, 111, 108, 105, 100];
for (let offset = 0; offset < 5 && offset + solid.length <= bytes.length; offset += 1) {
if (solid.every((value, index) => bytes[offset + index] === value)) return "ascii";
}
return "binary";
}
function getSafeExportName(fileName) {
return (
getDisplayName(fileName)
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
.trim() || "model"
);
}
function createModelExportObject(geometries, modelMatrix, fileName) {
const exportRoot = new THREE.Group();
exportRoot.name = getSafeExportName(fileName);
exportRoot.matrixAutoUpdate = false;
exportRoot.matrix.copy(modelMatrix);
geometries.forEach((geometry, index) => {
const isPointCloud = geometry.userData.primitiveType === "points";
const object = isPointCloud
? new THREE.Points(geometry, null)
: new THREE.Mesh(geometry, null);
object.name = exportRoot.name + (geometries.length > 1 ? "_part_" + (index + 1) : "");
exportRoot.add(object);
});
exportRoot.updateMatrixWorld(true);
return exportRoot;
}
function serializeModelExport(exportObject, sourceFile) {
let data;
let mimeType = "application/octet-stream";
if (sourceFile.extension === "obj") {
data = new OBJExporter().parse(exportObject);
mimeType = "text/plain;charset=utf-8";
} else if (sourceFile.extension === "ply") {
const binary = sourceFile.encoding !== "ascii";
data = new PLYExporter().parse(exportObject, null, {
binary,
littleEndian: sourceFile.encoding === "binary_little_endian",
});
if (!binary) mimeType = "text/plain;charset=utf-8";
} else if (sourceFile.extension === "stl") {
const binary = sourceFile.encoding === "binary";
data = new STLExporter().parse(exportObject, { binary });
if (!binary) mimeType = "text/plain;charset=utf-8";
} else {
throw new Error("The imported model format cannot be exported.");
}
if (data === null || data === undefined) {
throw new Error("The model could not be encoded in its original format.");
}
const baseName = getSafeExportName(sourceFile.name);
return {
data,
mimeType,
fileName: baseName + "-meshtozero." + sourceFile.extension,
};
}
function getNiceScale(value) {
if (!Number.isFinite(value) || value <= 0) return 1;
const exponent = 10 ** Math.floor(Math.log10(value));
const fraction = value / exponent;
if (fraction <= 1) return exponent;
if (fraction <= 2) return 2 * exponent;
if (fraction <= 5) return 5 * exponent;
return 10 * exponent;
}
function createFallbackAxis(normal) {
const candidates = [
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(0, 0, 1),
];
candidates.sort((left, right) => Math.abs(left.dot(normal)) - Math.abs(right.dot(normal)));
return candidates[0].addScaledVector(normal, -candidates[0].dot(normal)).normalize();
}
function normalizePlaneBasis(normal, preferredXAxis) {
const normalizedNormal = normal.clone();
if (normalizedNormal.lengthSq() <= GEOMETRY_EPSILON ** 2) {
throw new Error("The selected references do not define a stable plane.");
}
normalizedNormal.normalize();
const xAxis = preferredXAxis?.clone() || createFallbackAxis(normalizedNormal);
xAxis.addScaledVector(normalizedNormal, -xAxis.dot(normalizedNormal));
if (xAxis.lengthSq() <= GEOMETRY_EPSILON ** 2) {
xAxis.copy(createFallbackAxis(normalizedNormal));
} else {
xAxis.normalize();
}
const yAxis = normalizedNormal.clone().cross(xAxis).normalize();
return { normal: normalizedNormal, xAxis, yAxis };
}
function createNormalAlignmentDelta(sourceNormal, targetNormal, preferredAxis) {
const source = sourceNormal.clone().normalize();
const target = targetNormal.clone().normalize();
const dot = THREE.MathUtils.clamp(source.dot(target), -1, 1);
if (dot >= 1 - GEOMETRY_EPSILON) {
return new THREE.Quaternion();
}
if (dot <= -1 + GEOMETRY_EPSILON) {
const axis = preferredAxis?.clone() || createFallbackAxis(source);
axis.addScaledVector(source, -axis.dot(source));
if (axis.lengthSq() <= GEOMETRY_EPSILON ** 2) {
axis.copy(createFallbackAxis(source));
} else {
axis.normalize();
}
return new THREE.Quaternion().setFromAxisAngle(axis, Math.PI);
}
return new THREE.Quaternion().setFromUnitVectors(source, target).normalize();
}
function jacobiEigenDecomposition(matrix) {
const values = matrix.map((row) => row.slice());
const vectors = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
for (let iteration = 0; iteration < 32; iteration += 1) {
let p = 0;
let q = 1;
let largest = Math.abs(values[0][1]);
for (const [row, column] of [
[0, 2],
[1, 2],
]) {
const candidate = Math.abs(values[row][column]);
if (candidate > largest) {
largest = candidate;
p = row;
q = column;
}
}
if (largest <= 1e-14) break;
const app = values[p][p];
const aqq = values[q][q];
const apq = values[p][q];
const angle = 0.5 * Math.atan2(2 * apq, aqq - app);
const cosine = Math.cos(angle);
const sine = Math.sin(angle);
for (let index = 0; index < 3; index += 1) {
if (index === p || index === q) continue;
const aip = values[index][p];
const aiq = values[index][q];
values[index][p] = cosine * aip - sine * aiq;
values[p][index] = values[index][p];
values[index][q] = sine * aip + cosine * aiq;
values[q][index] = values[index][q];
}
values[p][p] =
cosine * cosine * app - 2 * sine * cosine * apq + sine * sine * aqq;
values[q][q] =
sine * sine * app + 2 * sine * cosine * apq + cosine * cosine * aqq;
values[p][q] = 0;
values[q][p] = 0;
for (let index = 0; index < 3; index += 1) {
const vip = vectors[index][p];
const viq = vectors[index][q];
vectors[index][p] = cosine * vip - sine * viq;
vectors[index][q] = sine * vip + cosine * viq;
}
}
return [0, 1, 2]
.map((index) => ({
value: Math.max(0, values[index][index]),
vector: new THREE.Vector3(
vectors[0][index],
vectors[1][index],
vectors[2][index],
).normalize(),
}))
.sort((left, right) => left.value - right.value);
}
function fitPlaneToPoints(points) {
const origin = points.reduce(
(sum, point) => sum.add(point),
new THREE.Vector3(),
).multiplyScalar(1 / points.length);
const covariance = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
];
for (const point of points) {
const delta = point.clone().sub(origin);
covariance[0][0] += delta.x * delta.x;
covariance[0][1] += delta.x * delta.y;
covariance[0][2] += delta.x * delta.z;
covariance[1][1] += delta.y * delta.y;
covariance[1][2] += delta.y * delta.z;
covariance[2][2] += delta.z * delta.z;
}
covariance[1][0] = covariance[0][1];
covariance[2][0] = covariance[0][2];
covariance[2][1] = covariance[1][2];
const eigen = jacobiEigenDecomposition(covariance);
const largestVariance = eigen[2].value;
if (largestVariance <= GEOMETRY_EPSILON || eigen[1].value <= largestVariance * 1e-10) {
throw new Error("Choose points that are not all on one line.");
}
const basis = normalizePlaneBasis(eigen[0].vector, eigen[2].vector);
return { origin, ...basis };
}
function fitPlanarSurfaceAtPoint(
points,
seed,
{
preferredNormal = null,
orientationHint = null,
xAxisHint = null,
absoluteTolerance = GEOMETRY_EPSILON,
} = {},
) {
if (points.length < 3) {
throw new Error("The selected area needs at least three nearby points.");
}
const safeAbsoluteTolerance = Math.max(absoluteTolerance, GEOMETRY_EPSILON);
const samples = points
.map((point) => ({
point,
distanceSq: point.distanceToSquared(seed),
}))
.sort((left, right) => left.distanceSq - right.distanceSq)
.slice(0, LOCAL_PLANE_FIT_NEIGHBORS);
const neighborhood = samples.map((sample) => sample.point);
const nonzeroSamples = samples.filter(
(sample) => sample.distanceSq > safeAbsoluteTolerance ** 2,
);
if (nonzeroSamples.length < 2) {
throw new Error("The selected area needs three distinct non-collinear points.");
}
const radius = Math.sqrt(samples.at(-1).distanceSq);
const densityCount = Math.min(nonzeroSamples.length, 16);
const densityRadius = Math.sqrt(nonzeroSamples[densityCount - 1].distanceSq);
const spacing = densityRadius / Math.sqrt(densityCount);
const distanceTolerance = Math.max(
safeAbsoluteTolerance,
spacing * 0.45,
radius * 0.006,
);
const getInliers = (origin, normal, multiplier = 1) =>
neighborhood.filter(
(point) =>
Math.abs(point.clone().sub(origin).dot(normal)) <= distanceTolerance * multiplier,
);
let inliers = [];
if (preferredNormal?.lengthSq() > GEOMETRY_EPSILON ** 2) {
const normal = preferredNormal.clone().normalize();
inliers = getInliers(seed, normal);
if (inliers.length < 3) inliers = getInliers(seed, normal, 2);
} else {
let bestCandidate = null;
const considerCandidate = (origin, normal) => {
const candidateInliers = getInliers(origin, normal);
if (candidateInliers.length < 3) return;
const residual = candidateInliers.reduce((sum, point) => {
const distance = point.clone().sub(origin).dot(normal);
return sum + distance * distance;
}, 0);
if (
!bestCandidate ||
candidateInliers.length > bestCandidate.inliers.length ||
(candidateInliers.length === bestCandidate.inliers.length &&
residual < bestCandidate.residual)
) {
bestCandidate = { inliers: candidateInliers, residual };
}
};
try {
const initialFit = fitPlaneToPoints(neighborhood);
considerCandidate(initialFit.origin, initialFit.normal);
} catch {
// Pair candidates below can still recover a plane when the full neighborhood is ambiguous.
}
const ransacSamples = nonzeroSamples.slice(0, LOCAL_PLANE_RANSAC_NEIGHBORS);
for (let firstIndex = 0; firstIndex < ransacSamples.length - 1; firstIndex += 1) {
const first = ransacSamples[firstIndex].point.clone().sub(seed);
for (
let secondIndex = firstIndex + 1;
secondIndex < ransacSamples.length;
secondIndex += 1
) {
const second = ransacSamples[secondIndex].point.clone().sub(seed);
const normal = first.clone().cross(second);
const maximumArea = Math.sqrt(first.lengthSq() * second.lengthSq());
if (
maximumArea <= safeAbsoluteTolerance ** 2 ||
normal.length() <= maximumArea * 1e-4
) {
continue;
}
considerCandidate(seed, normal.normalize());
}
}
inliers = bestCandidate?.inliers || [];
}
const minimumInliers =
neighborhood.length < 8 ? 3 : Math.max(6, Math.ceil(neighborhood.length * 0.4));
if (inliers.length < (preferredNormal ? 3 : minimumInliers)) {
throw new Error(
"No flat surface was found around that point. Click farther from an edge or use Best Fit.",
);
}
let fitted = null;
for (let iteration = 0; iteration < 3; iteration += 1) {
fitted = fitPlaneToPoints(inliers);
const refined = getInliers(fitted.origin, fitted.normal, 1.5);
if (refined.length < 3 || refined.length === inliers.length) break;
inliers = refined;
}
fitted = fitPlaneToPoints(inliers);
const orientation = orientationHint || preferredNormal;
const normal = fitted.normal.clone();
if (orientation?.lengthSq() > GEOMETRY_EPSILON ** 2 && normal.dot(orientation) < 0) {
normal.negate();
}
let preferredXAxis = fitted.xAxis;
if (xAxisHint?.lengthSq() > GEOMETRY_EPSILON ** 2) {
const projectedXAxis = xAxisHint
.clone()
.addScaledVector(normal, -xAxisHint.dot(normal));
if (projectedXAxis.lengthSq() > GEOMETRY_EPSILON ** 2) {
preferredXAxis = projectedXAxis.normalize();
}
}
const basis = normalizePlaneBasis(normal, preferredXAxis);
const origin = seed
.clone()
.addScaledVector(
basis.normal,
-seed.clone().sub(fitted.origin).dot(basis.normal),
);
let squaredError = 0;
let planarExtentSq = 0;
for (const point of inliers) {
const delta = point.clone().sub(fitted.origin);
const signedDistance = delta.dot(basis.normal);
squaredError += signedDistance * signedDistance;
planarExtentSq = Math.max(
planarExtentSq,
Math.max(0, delta.lengthSq() - signedDistance * signedDistance),
);
}
const rmsError = Math.sqrt(squaredError / inliers.length);
const planarExtent = Math.sqrt(planarExtentSq);
if (
planarExtent <= safeAbsoluteTolerance ||
(rmsError > safeAbsoluteTolerance * 2 && rmsError / planarExtent > 0.035)
) {
throw new Error(
"The selected neighborhood is not flat enough. Click a broader planar area.",
);
}
return {
origin,
normal: basis.normal,
xAxis: basis.xAxis,
pointCount: inliers.length,
rmsError,
};
}
function addNearestPointSample(heap, keys, sample, maximum) {
if (keys.has(sample.key)) return;
if (heap.length < maximum) {
heap.push(sample);
keys.add(sample.key);
let childIndex = heap.length - 1;
while (childIndex > 0) {
const parentIndex = Math.floor((childIndex - 1) / 2);
if (heap[parentIndex].distanceSq >= heap[childIndex].distanceSq) break;
[heap[parentIndex], heap[childIndex]] = [heap[childIndex], heap[parentIndex]];
childIndex = parentIndex;
}
return;
}
if (sample.distanceSq >= heap[0].distanceSq) return;
keys.delete(heap[0].key);
heap[0] = sample;
keys.add(sample.key);
let parentIndex = 0;
while (true) {
const leftIndex = parentIndex * 2 + 1;
const rightIndex = leftIndex + 1;
let largestIndex = parentIndex;
if (
leftIndex < heap.length &&
heap[leftIndex].distanceSq > heap[largestIndex].distanceSq
) {
largestIndex = leftIndex;
}
if (
rightIndex < heap.length &&
heap[rightIndex].distanceSq > heap[largestIndex].distanceSq
) {
largestIndex = rightIndex;
}
if (largestIndex === parentIndex) break;
[heap[parentIndex], heap[largestIndex]] = [heap[largestIndex], heap[parentIndex]];
parentIndex = largestIndex;
}
}
function getPrincipalFrame(points) {
const center = points
.reduce((sum, point) => sum.add(point), new THREE.Vector3())
.multiplyScalar(1 / points.length);
const covariance = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
];
for (const point of points) {
const delta = point.clone().sub(center);
covariance[0][0] += delta.x * delta.x;
covariance[0][1] += delta.x * delta.y;
covariance[0][2] += delta.x * delta.z;
covariance[1][1] += delta.y * delta.y;
covariance[1][2] += delta.y * delta.z;
covariance[2][2] += delta.z * delta.z;
}
covariance[1][0] = covariance[0][1];
covariance[2][0] = covariance[0][2];
covariance[2][1] = covariance[1][2];
const eigen = jacobiEigenDecomposition(covariance);
if (eigen[2].value <= GEOMETRY_EPSILON) {
throw new Error("The model does not contain enough spatial extent to determine an orientation.");
}
const xAxis = eigen[2].vector.clone();
const preferredYAxis =
eigen[1].value > eigen[2].value * 1e-12
? eigen[1].vector.clone()
: createFallbackAxis(xAxis);
const zAxis = xAxis.clone().cross(preferredYAxis).normalize();
const yAxis = zAxis.clone().cross(xAxis).normalize();
return {
xAxis,
yAxis,
zAxis,
variances: new THREE.Vector3(eigen[2].value, eigen[1].value, eigen[0].value),
};
}
function canonicalDirectionKey(direction) {
const values = [direction.x, direction.y, direction.z];
let dominantIndex = 0;
for (let index = 1; index < values.length; index += 1) {
if (Math.abs(values[index]) > Math.abs(values[dominantIndex])) dominantIndex = index;
}
const sign = values[dominantIndex] < 0 ? -1 : 1;
return values.map((value) => Math.round(value * sign * 1e6)).join(":");
}
function evaluateOrientedFrame(points, frame) {
const minimum = new THREE.Vector3(Infinity, Infinity, Infinity);
const maximum = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
for (const point of points) {
const x = point.dot(frame.xAxis);
const y = point.dot(frame.yAxis);
const z = point.dot(frame.zAxis);
minimum.x = Math.min(minimum.x, x);
minimum.y = Math.min(minimum.y, y);
minimum.z = Math.min(minimum.z, z);
maximum.x = Math.max(maximum.x, x);
maximum.y = Math.max(maximum.y, y);
maximum.z = Math.max(maximum.z, z);
}
const size = maximum.clone().sub(minimum);
const centerCoordinates = minimum.clone().add(maximum).multiplyScalar(0.5);
const center = new THREE.Vector3()
.addScaledVector(frame.xAxis, centerCoordinates.x)
.addScaledVector(frame.yAxis, centerCoordinates.y)
.addScaledVector(frame.zAxis, centerCoordinates.z);
const dimensionFloor = Math.max(size.x, size.y, size.z, 1) * 1e-9;
const score =
Math.max(size.x, dimensionFloor) *
Math.max(size.y, dimensionFloor) *
Math.max(size.z, dimensionFloor);
return { ...frame, center, size, score };
}
function sampleCandidateFrames(frames, limit) {
if (frames.length <= limit) return frames;
const sampled = [frames[0]];
const remainingLimit = limit - 1;
for (let index = 0; index < remainingLimit; index += 1) {
const sourceIndex = 1 + Math.floor((index * (frames.length - 1)) / remainingLimit);
sampled.push(frames[sourceIndex]);
}
return sampled;
}
function findBestOrientedFrame(points) {
const principal = getPrincipalFrame(points);
const frames = new Map();
const addFrame = (normal, preferredXAxis) => {
try {
const basis = normalizePlaneBasis(normal, preferredXAxis);
const key =
canonicalDirectionKey(basis.normal) + "|" + canonicalDirectionKey(basis.xAxis);
if (!frames.has(key)) {
frames.set(key, {
xAxis: basis.xAxis,
yAxis: basis.yAxis,
zAxis: basis.normal,
});
}
} catch {
// Degenerate hull edges are ignored; the PCA frame remains available as a fallback.
}
};
addFrame(principal.zAxis, principal.xAxis);
let boundsPoints = points;
try {
const hull = new ConvexHull().setFromPoints(points);
if (hull.faces.length) {
const hullPointSet = new Set();
for (const face of hull.faces) {
let edge = face.edge;
do {
const tail = edge.tail()?.point;
const head = edge.head()?.point;
if (tail && head) {
hullPointSet.add(tail);
hullPointSet.add(head);
addFrame(face.normal, head.clone().sub(tail));
}
edge = edge.next;
} while (edge && edge !== face.edge);
}
if (hullPointSet.size) boundsPoints = [...hullPointSet];
}
} catch (error) {
console.warn("Convex hull orientation analysis fell back to principal axes:", error);
}
const candidateFrames = sampleCandidateFrames(
[...frames.values()],
MAX_OBB_CANDIDATE_FRAMES,
);
let best = null;
for (const frame of candidateFrames) {
const evaluated = evaluateOrientedFrame(boundsPoints, frame);
if (!best || evaluated.score < best.score) best = evaluated;
}
return {
...best,
hullVertexCount: boundsPoints.length,
candidateFrameCount: candidateFrames.length,
};
}
function orderFrameAxesByExtent(frame) {
const axes = [
{ direction: frame.xAxis.clone(), size: frame.size.x },
{ direction: frame.yAxis.clone(), size: frame.size.y },
{ direction: frame.zAxis.clone(), size: frame.size.z },
].sort((left, right) => right.size - left.size);
const xAxis = axes[0].direction.normalize();
let zAxis = axes[2].direction.normalize();
let yAxis = zAxis.clone().cross(xAxis).normalize();
if (yAxis.dot(axes[1].direction) < 0) {
zAxis = zAxis.negate();
yAxis = zAxis.clone().cross(xAxis).normalize();
}
return {
xAxis,
yAxis,
zAxis,
size: new THREE.Vector3(axes[0].size, axes[1].size, axes[2].size),
};
}
function findStableModelFrame(points) {
const principal = getPrincipalFrame(points);
const hasDistinctLongAxis =
principal.variances.x > principal.variances.y * PRINCIPAL_AXIS_SEPARATION_RATIO;
const hasDistinctShortAxis =
principal.variances.y >
Math.max(principal.variances.z, GEOMETRY_EPSILON) * PRINCIPAL_AXIS_SEPARATION_RATIO;
if (hasDistinctLongAxis && hasDistinctShortAxis) {
return evaluateOrientedFrame(points, principal);
}
const oriented = orderFrameAxesByExtent(findBestOrientedFrame(points));
const zAxis = (hasDistinctShortAxis ? principal.zAxis : oriented.zAxis)
.clone()
.normalize();
const xAxis = (hasDistinctLongAxis ? principal.xAxis : oriented.xAxis).clone();
xAxis.addScaledVector(zAxis, -xAxis.dot(zAxis));
if (xAxis.lengthSq() <= GEOMETRY_EPSILON ** 2) {
xAxis.copy(createFallbackAxis(zAxis));
} else {
xAxis.normalize();
}
const yAxis = zAxis.clone().cross(xAxis).normalize();
return evaluateOrientedFrame(points, { xAxis, yAxis, zAxis });
}
function createAutomaticAxisPlaneDefinitions(frame, scale) {
if ([scale.x, scale.y, scale.z].some((value) => Math.abs(value) <= GEOMETRY_EPSILON)) {
throw new Error("Automatic model axes require a non-zero scale on every axis.");
}
const ordered = orderFrameAxesByExtent(frame);
const origin = new THREE.Vector3(
frame.center.x / scale.x,
frame.center.y / scale.y,
frame.center.z / scale.z,
);
const toModelDirection = (direction) =>
new THREE.Vector3(
direction.x / scale.x,
direction.y / scale.y,
direction.z / scale.z,
).normalize();
const toModelNormal = (normal) => normal.clone().multiply(scale).normalize();
const xAxis = toModelDirection(ordered.xAxis);
const yAxis = toModelDirection(ordered.yAxis);
return [
{
label: "Top",
origin: origin.clone(),
normal: toModelNormal(ordered.zAxis),
xAxis,
},
{
label: "Front",
origin: origin.clone(),
normal: toModelNormal(ordered.yAxis),
xAxis,
},
{
label: "Right",
origin: origin.clone(),
normal: toModelNormal(ordered.xAxis),
xAxis: yAxis,
},
];
}
function createOrientedBoundsPlaneDefinitions(frame, scale) {
if ([scale.x, scale.y, scale.z].some((value) => Math.abs(value) <= GEOMETRY_EPSILON)) {
throw new Error("Oriented bounds require a non-zero scale on every axis.");
}
const ordered = orderFrameAxesByExtent(frame);
const halfSize = ordered.size.clone().multiplyScalar(0.5);
const toModelPoint = (point) =>
new THREE.Vector3(
point.x / scale.x,
point.y / scale.y,
point.z / scale.z,
);
const toModelDirection = (direction) =>
new THREE.Vector3(
direction.x / scale.x,
direction.y / scale.y,
direction.z / scale.z,
).normalize();
const toModelNormal = (normal) => normal.clone().multiply(scale).normalize();
const createFace = (label, outwardDirection, distance, tangentDirection) => ({
label,
kind: "face",
origin: toModelPoint(
frame.center.clone().addScaledVector(outwardDirection, distance),
),
normal: toModelNormal(outwardDirection),
xAxis: toModelDirection(tangentDirection),
});
const createCenter = (label, normal, tangentDirection) => ({
label,
kind: "center",
origin: toModelPoint(frame.center),
normal: toModelNormal(normal),
xAxis: toModelDirection(tangentDirection),
});
const negativeX = ordered.xAxis.clone().negate();
const negativeY = ordered.yAxis.clone().negate();
const negativeZ = ordered.zAxis.clone().negate();
const faces = [
createFace("Left", negativeX, halfSize.x, ordered.yAxis),
createFace("Right", ordered.xAxis, halfSize.x, ordered.yAxis),
createFace("Back", negativeY, halfSize.y, ordered.xAxis),
createFace("Front", ordered.yAxis, halfSize.y, ordered.xAxis),
createFace("Bottom", negativeZ, halfSize.z, ordered.xAxis),
createFace("Top", ordered.zAxis, halfSize.z, ordered.xAxis),
];
const centers = [
createCenter("Right Center", ordered.xAxis, ordered.yAxis),
createCenter("Front Center", ordered.yAxis, ordered.xAxis),
createCenter("Top Center", ordered.zAxis, ordered.xAxis),
];
const corners = [];
for (const xSign of [-1, 1]) {
for (const ySign of [-1, 1]) {
for (const zSign of [-1, 1]) {
const corner = frame.center
.clone()
.addScaledVector(ordered.xAxis, xSign * halfSize.x)
.addScaledVector(ordered.yAxis, ySign * halfSize.y)
.addScaledVector(ordered.zAxis, zSign * halfSize.z);
corners.push(toModelPoint(corner));
}
}
}
return {
faces,
centers,
corners,
center: toModelPoint(frame.center),
size: ordered.size.clone(),
};
}
function createRotationFromBasis(xAxis, yAxis, zAxis) {
const basisMatrix = new THREE.Matrix4().makeBasis(xAxis, yAxis, zAxis);
return new THREE.Quaternion().setFromRotationMatrix(basisMatrix).invert().normalize();
}
// Keep source vertices untouched while rotating and scaling around the model center.
function calculateRootPositionAroundPivot(modelPosition, rotation, scale, pivot) {
const transformedPivot = pivot.clone().multiply(scale).applyQuaternion(rotation);
return modelPosition.clone().add(pivot).sub(transformedPivot);
}
function calculateTransformGizmoPosition(modelPosition, pivot) {
return pivot.clone().add(modelPosition);
}
function calculateModelPositionFromTransformGizmo(gizmoPosition, pivot) {
return gizmoPosition.clone().sub(pivot);
}
function formatCoordinate(value) {
if (!Number.isFinite(value)) return "0";
const absoluteValue = Math.abs(value);
if (absoluteValue < 1e-9) return "0.000";
if ((absoluteValue > 0 && absoluteValue < 0.001) || absoluteValue >= 100000) {
return value.toExponential(3);
}
return value.toFixed(3);
}
function chooseAlignmentPlaneHit(sourceHits, targetHits) {
const sourceId = sourceHits[0]?.object?.userData?.alignmentPlaneId;
if (sourceId) return { kind: "source", id: sourceId };
const targetId = targetHits[0]?.object?.userData?.alignmentTargetId;
if (targetId) return { kind: "target", id: targetId };
return null;
}
class ThreeViewport {
constructor(targetCanvas) {
this.canvas = targetCanvas;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(36, 1, 0.1, 100);
this.camera.up.set(0, 0, 1);
this.renderer = new THREE.WebGLRenderer({
canvas: targetCanvas,
antialias: true,
alpha: false,
powerPreference: "high-performance",
});
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.controls = new OrbitControls(this.camera, targetCanvas);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.075;
this.controls.minPolarAngle = 0;
this.controls.maxPolarAngle = Math.PI;
this.controls.screenSpacePanning = true;
this.controls.zoomToCursor = false;
this.controls.mouseButtons.LEFT = null;
this.controls.mouseButtons.MIDDLE = THREE.MOUSE.ROTATE;
this.controls.mouseButtons.RIGHT = THREE.MOUSE.PAN;
this.controls.listenToKeyEvents(window);
this.loaders = {