-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2463 lines (2045 loc) · 73.6 KB
/
index.js
File metadata and controls
2463 lines (2045 loc) · 73.6 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
// qs_box_takeoff_multi.js
// Multi-box QS takeoff POC with:
// - Draw MULTIPLE boxes (click start -> click finish)
// - Select / multi-select (click = select, Ctrl/Cmd+click = toggle, click empty = clear)
// - Click-drag-release to MOVE selected boxes on the ground plane
// - Push/Pull on ANY FACE of the active/selected box (enable checkbox)
// - Face hover highlight in Push/Pull mode
// - Axis lock while push/pulling: press X / Y / Z (press again to clear)
// - Delete selected objects: Delete / Backspace (ignored while typing in inputs)
//
// Requires your HTML to include an importmap for "three" + "three/addons/"
// and these UI element IDs: len, wid, hgt, baseY, snap, snapSize, pp, apply, clear, out
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
// -----------------------------
// Scene / Camera / Renderer
// -----------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b0c10);
// Perspective camera for 3D view
const perspectiveCamera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 1, 400000);
perspectiveCamera.position.set(8000, 6500, 8000);
// Orthographic camera for 2D views (plan, elevations)
const aspect = window.innerWidth / window.innerHeight;
const frustumSize = 20000; // Adjust to show appropriate area
const orthoCamera = new THREE.OrthographicCamera(
frustumSize * aspect / -2,
frustumSize * aspect / 2,
frustumSize / 2,
frustumSize / -2,
-100000,
100000
);
// Current active camera
let camera = perspectiveCamera;
let currentView = '3D'; // '3D', 'plan', 'front', 'rear', 'left', 'right'
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.domElement.style.touchAction = "none"; // avoid gesture stealing
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.screenSpacePanning = true;
// Mouse button configuration
controls.mouseButtons = {
LEFT: THREE.MOUSE.ROTATE,
MIDDLE: THREE.MOUSE.DOLLY,
RIGHT: THREE.MOUSE.PAN
};
// Touch configuration
controls.touches = {
ONE: THREE.TOUCH.ROTATE,
TWO: THREE.TOUCH.DOLLY_PAN
};
scene.add(new THREE.AmbientLight(0xffffff, 0.55));
const dir = new THREE.DirectionalLight(0xffffff, 0.85);
dir.position.set(6000, 9000, 3000);
scene.add(dir);
scene.add(new THREE.GridHelper(50000, 100, 0x2b2f3a, 0x1a1d24));
// Make origin obvious (axes + dot)
const axes = new THREE.AxesHelper(6000);
axes.position.set(0, 5, 0);
scene.add(axes);
const originDot = new THREE.Mesh(
new THREE.SphereGeometry(60, 18, 18),
new THREE.MeshStandardMaterial({ color: 0xffffff })
);
originDot.position.set(0, 20, 0);
scene.add(originDot);
// Raycast ground plane (keep visible=true; opacity=0 for invisibility)
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(400000, 400000),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0.0,
depthWrite: false,
side: THREE.DoubleSide
})
);
ground.rotation.x = -Math.PI / 2;
ground.visible = true;
scene.add(ground);
// -----------------------------
// UI elements
// -----------------------------
const lenEl = document.getElementById("len");
const widEl = document.getElementById("wid");
const hgtEl = document.getElementById("hgt");
const baseYEl = document.getElementById("baseY");
const snapEl = document.getElementById("snap");
const snapSizeEl = document.getElementById("snapSize");
const angleSnapEl = document.getElementById("angleSnap");
const angleSnapIncrementEl = document.getElementById("angleSnapIncrement");
const customAngleEl = document.getElementById("customAngle");
const ppEl = document.getElementById("pp");
const wallModeBtn = document.getElementById("wallModeBtn");
const slabModeBtn = document.getElementById("slabModeBtn");
const outEl = document.getElementById("out");
const applyBtn = document.getElementById("apply");
const clearBtn = document.getElementById("clear");
const resetOriginBtn = document.getElementById("resetOrigin");
const hintBoxMode = document.getElementById("hintBoxMode");
const hintWallMode = document.getElementById("hintWallMode");
// View buttons
const viewPlanBtn = document.getElementById("viewPlan");
const viewFrontBtn = document.getElementById("viewFront");
const viewRearBtn = document.getElementById("viewRear");
const viewLeftBtn = document.getElementById("viewLeft");
const viewRightBtn = document.getElementById("viewRight");
const view3DBtn = document.getElementById("view3D");
// Drawing mode state - independent toggles
let wallModeEnabled = false;
let slabModeEnabled = false;
// Mode button handlers
function updateModeButtons() {
// Update button styles
if (wallModeBtn) {
wallModeBtn.className = wallModeEnabled ? 'btn primary mode-btn' : 'btn secondary mode-btn';
}
if (slabModeBtn) {
slabModeBtn.className = slabModeEnabled ? 'btn primary mode-btn' : 'btn secondary mode-btn';
}
// Update hints
if (hintBoxMode) hintBoxMode.style.display = slabModeEnabled ? "inline" : "none";
if (hintWallMode) hintWallMode.style.display = wallModeEnabled ? "inline" : "none";
}
// Wire up mode buttons (independent toggles)
if (wallModeBtn) {
wallModeBtn.addEventListener('click', () => {
wallModeEnabled = !wallModeEnabled;
// Turn off slab if turning on wall
if (wallModeEnabled) slabModeEnabled = false;
updateModeButtons();
});
}
if (slabModeBtn) {
slabModeBtn.addEventListener('click', () => {
slabModeEnabled = !slabModeEnabled;
// Turn off wall if turning on slab
if (slabModeEnabled) wallModeEnabled = false;
updateModeButtons();
});
}
// Set initial mode - start with neither enabled
wallModeEnabled = false;
slabModeEnabled = false;
updateModeButtons();
// -----------------------------
// Dimension Modal (HTML/CSS based)
// -----------------------------
const dimModal = document.getElementById("dimModal");
const dlU = document.getElementById("dl_U");
const dlV = document.getElementById("dl_V");
const dlW = document.getElementById("dl_W");
const dlBaseY = document.getElementById("dl_baseY");
const dlApply = document.getElementById("dl_apply");
const dlClear = document.getElementById("dl_clear");
// drawing locks
const drawLock = { active: false, L: null, W: null, H: null, baseY: null };
// Live display in modal inputs (only when user hasn't manually typed)
const dlManual = { L: false, W: false, H: false };
let suppressModalAuto = false;
// Manual input tracking for UVW (wall mode)
const uvwManual = { U: false, V: false, W: false };
dlU?.addEventListener("input", () => {
if (suppressModalAuto) return;
dlManual.L = dlU.value !== "";
uvwManual.U = dlU.value !== "";
// Update preview immediately if drawing
if (drawing && startPt && lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
updatePreviewRect(startPt, currentPt);
}
// Update wall preview if in wall mode
if (wallDrawing.active && wallDrawing.step === 1 && dlU.value) {
const val = Number(dlU.value);
if (val > 0 && wallDrawing.U) {
wallDrawing.U.length = val;
updateWallPreview();
}
}
});
dlV?.addEventListener("input", () => {
if (suppressModalAuto) return;
dlManual.W = dlV.value !== "";
uvwManual.V = dlV.value !== "";
// Update preview immediately if drawing
if (drawing && startPt && lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
updatePreviewRect(startPt, currentPt);
}
// Update wall preview if in wall mode
if (wallDrawing.active && wallDrawing.step === 2 && dlV.value) {
const val = Number(dlV.value);
if (val >= 0) {
wallDrawing.V.length = val;
updateWallPreview();
}
}
});
dlW?.addEventListener("input", () => {
if (suppressModalAuto) return;
dlManual.H = dlW.value !== "";
uvwManual.W = dlW.value !== "";
// Update wall preview if in wall mode
if (wallDrawing.active && wallDrawing.step === 3 && dlW.value) {
const val = Number(dlW.value);
if (val > 0) {
wallDrawing.W.length = val;
updateWallPreview();
}
}
});
// Update modal fields with relative deltas from start point to current mouse point.
// Length shows |ΔX|, Width shows |ΔZ|. Height shows current UI height (hgtEl) unless user overrides.
// Sidebar/manual overrides (len/wid) while drawing:
// - If user types a value, it overrides the mouse delta
// - If user clears the field, it reverts to mouse delta
const sbManual = { L: false, W: false };
let suppressSidebarAuto = false;
function setSidebarLenWid(L, W) {
if (!lenEl || !widEl) return;
suppressSidebarAuto = true;
try {
if (!sbManual.L) lenEl.value = String(Math.round(L));
if (!sbManual.W) widEl.value = String(Math.round(W));
} finally {
suppressSidebarAuto = false;
}
}
lenEl?.addEventListener("input", () => {
if (suppressSidebarAuto) return;
sbManual.L = lenEl.value !== "";
// if drawing, update preview immediately
if (drawing && startPt && lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
updatePreviewRect(startPt, currentPt);
}
});
widEl?.addEventListener("input", () => {
if (suppressSidebarAuto) return;
sbManual.W = widEl.value !== "";
if (drawing && startPt && lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
updatePreviewRect(startPt, currentPt);
}
});
// When modal L/W inputs change, update preview immediately
dlU?.addEventListener("input", () => {
if (drawing && startPt && lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
updatePreviewRect(startPt, currentPt);
}
});
dlW?.addEventListener("input", () => {
if (drawing && startPt && lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
updatePreviewRect(startPt, currentPt);
}
});
function getOverrideAbsNumber(el) {
if (!el) return null;
const v = el.value;
if (v === "" || v == null) return null;
const n = Number(v);
if (!Number.isFinite(n)) return null;
return Math.abs(n);
}
function updateSidebarLive(mousePointOnGround) {
if (!drawing || !startPt || !mousePointOnGround) return;
const dx = mousePointOnGround.x - startPt.x;
const dz = mousePointOnGround.z - startPt.z;
setSidebarLenWid(Math.abs(dx), Math.abs(dz));
}
function updateDimModalLive(mousePointOnGround) {
if (!dimModal) return;
const visible = !dimModal.classList.contains("hidden") && dimModal.style.display !== "none";
if (!visible) return;
if (!drawing || !startPt || !mousePointOnGround) return;
const dx = mousePointOnGround.x - startPt.x;
const dz = mousePointOnGround.z - startPt.z;
// If the field is empty, it is always "mouse-driven" (reverts automatically when cleared)
if (dlU && dlU.value === "" && dlU !== document.activeElement) dlU.value = String(Math.round(Math.abs(dx)));
if (dlW && dlW.value === "" && dlW !== document.activeElement) dlW.value = String(Math.round(Math.abs(dz)));
// If user hasn't manually typed, keep mirroring mouse
if (!dlManual.L && dlU && dlU !== document.activeElement) dlU.value = String(Math.round(Math.abs(dx)));
if (!dlManual.W && dlW && dlW !== document.activeElement) dlW.value = String(Math.round(Math.abs(dz)));
// Height mirrors sidebar height unless user overrides
if (!dlManual.H && dlV && dlV !== document.activeElement && hgtEl) {
dlV.value = String(Math.round(Number(hgtEl.value) || 0));
}
}
function showDimModal() {
if (!dimModal) return;
dimModal.classList.remove("hidden");
dimModal.style.display = "block";
dimModal.setAttribute("aria-hidden", "false");
// Focus LENGTH field reliably after display change
requestAnimationFrame(() => {
dlU?.focus({ preventScroll: true });
// Select existing value so typing overwrites
if (typeof dlU?.select === "function") dlU.select();
});
}
function hideDimModal() {
if (!dimModal) return;
dimModal.classList.add("hidden");
dimModal.style.display = "none";
dimModal.setAttribute("aria-hidden", "true");
}
function clearDimModal() {
suppressModalAuto = true;
try {
if (dlU) dlU.value = "";
if (dlV) dlV.value = "";
if (dlW) dlW.value = "";
if (dlBaseY) dlBaseY.value = "";
} finally {
suppressModalAuto = false;
}
drawLock.active = false;
drawLock.L = drawLock.W = drawLock.H = drawLock.baseY = null;
// Reset manual typing flags for next shape
dlManual.L = false;
dlManual.W = false;
dlManual.H = false;
uvwManual.U = false;
uvwManual.V = false;
uvwManual.W = false;
sbManual.L = false;
sbManual.W = false;
}
function applyDimModal() {
// If not currently drawing, do nothing
if (!drawing || !startPt) return;
// Apply dimension locks
drawLock.active = true;
drawLock.L = (dlU.value === "") ? null : Math.max(1, Number(dlU.value));
drawLock.W = (dlW.value === "") ? null : Math.max(1, Number(dlW.value));
drawLock.H = (dlV.value === "") ? null : Math.max(0, Number(dlV.value));
drawLock.baseY = (dlBaseY.value === "") ? null : Number(dlBaseY.value);
// sync UI if user typed H/baseY
if (drawLock.H != null && hgtEl) hgtEl.value = String(Math.round(drawLock.H));
if (drawLock.baseY != null && baseYEl) baseYEl.value = String(Math.round(drawLock.baseY));
// Complete the shape (same logic as second mouse click)
if (lastGroundPoint) {
currentPt = computeEndpoint(startPt, lastGroundPoint);
} else if (currentPt) {
// Use existing currentPt if no ground point available
} else {
// Fallback: use start point
currentPt = startPt.clone();
}
updatePreviewRect(startPt, currentPt);
createBoxFromFootprint(startPt, currentPt);
drawing = false;
startPt = null;
currentPt = null;
clearPreview();
exportQuantities({ drawing: "finished" });
hideDimModal();
clearDimModal();
}
dlApply?.addEventListener("click", applyDimModal);
dlClear?.addEventListener("click", () => { clearDimModal(); dlManual.L = dlManual.W = dlManual.H = false; });
// Modal ENTER/ESC key handler (uses capture to run before other handlers)
window.addEventListener("keydown", (e) => {
const isMac = navigator.platform.toUpperCase().includes("MAC");
const mod = isMac ? e.metaKey : e.ctrlKey;
// Undo / Redo - work even with modal open (but not while typing in fields)
if (mod && e.key.toLowerCase() === "z" && !isTypingTarget(document.activeElement)) {
e.preventDefault();
if (e.shiftKey) doRedo(); // Cmd/Ctrl+Shift+Z
else doUndo(); // Cmd/Ctrl+Z
return;
}
if (mod && e.key.toLowerCase() === "y" && !isTypingTarget(document.activeElement)) {
e.preventDefault();
doRedo(); // Ctrl+Y
return;
}
if (!dimModal) return;
const isOpen = dimModal.getAttribute("aria-hidden") === "false";
if (!isOpen) return;
// ENTER / NUMPAD ENTER => Complete wall or apply
if (e.key === "Enter" || e.code === "NumpadEnter") {
if (e.metaKey || e.ctrlKey || e.altKey) return;
e.preventDefault();
// Wall mode: ENTER completes the wall (after all fields set)
if (wallDrawing.active) {
completeWall();
} else {
dlApply?.click();
}
return;
}
// ESC => cancel drawing
if (e.key === "Escape") {
e.preventDefault();
cancelDrawing();
}
}, { capture: true });
// -----------------------------
// State
// -----------------------------
const raycaster = new THREE.Raycaster();
const mouseNDC = new THREE.Vector2();
let drawing = false;
let startPt = null;
let currentPt = null;
let lastGroundPoint = null; // latest ground point under mouse (for live preview + overrides)
// Wall Mode (UVW Sequential) State
let wallDrawing = {
active: false,
step: 0, // 0=none, 1=U, 2=V, 3=W
origin: null, // Start point (THREE.Vector3)
U: null, // { direction: THREE.Vector3 (unit), length: number }
V: null, // { direction: THREE.Vector3 (unit), length: number }
W: null, // { direction: THREE.Vector3 (unit), length: number }
currentMousePt: null, // Latest mouse position
editingWall: null // Reference to wall being edited (null if creating new)
};
let drag = {
active: false,
pointerId: null,
plane: new THREE.Plane(new THREE.Vector3(0, 1, 0), 0),
offset: new THREE.Vector3(),
before: null
};
let pushPull = {
active: false,
pointerId: null,
face: null, // { id, clickedFaceN, dragPlane, startPoint, startDims, startCenter }
lockAxis: null, // 'x' | 'y' | 'z' | null
before: null
};
let customPan = {
active: false,
pointerId: null,
startX: 0,
startY: 0,
startTarget: new THREE.Vector3()
};
let nextId = 1;
// Box registry
/** @type {Array<{id:string, mesh:THREE.Mesh, meta:{baseY:number,height:number}}>} */
const objects = [];
// Selection set (IDs)
const selected = new Set();
// Materials / colors
const NORMAL_COLOR = 0x9aa4b2;
const SELECT_COLOR = 0xffd166;
// -----------------------------
// Preview rectangle (drawing)
// -----------------------------
const previewLineMat = new THREE.LineBasicMaterial({ color: 0x7dd3fc, transparent: true, opacity: 0.95 });
const previewLineGeom = new THREE.BufferGeometry();
const previewLine = new THREE.Line(previewLineGeom, previewLineMat);
previewLine.visible = false;
scene.add(previewLine);
// Snap indicator (shows when cursor is near snap point)
const snapIndicatorGeom = new THREE.SphereGeometry(200, 16, 16); // 200mm radius (was 100mm)
const snapIndicatorMat = new THREE.MeshBasicMaterial({
color: 0x00ff00, // Bright green (easier to see than magenta)
transparent: true,
opacity: 0.8,
depthTest: false
});
const snapIndicator = new THREE.Mesh(snapIndicatorGeom, snapIndicatorMat);
snapIndicator.visible = false;
scene.add(snapIndicator);
function clearPreview() {
previewLine.visible = false;
previewLineGeom.setAttribute("position", new THREE.Float32BufferAttribute([], 3));
snapIndicator.visible = false; // Hide snap indicator too
}
// -----------------------------
// Push/Pull hover face highlight
// -----------------------------
const hoverFaceMat = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0.25,
depthWrite: false,
side: THREE.DoubleSide
});
const hoverFaceMesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), hoverFaceMat);
hoverFaceMesh.visible = false;
scene.add(hoverFaceMesh);
// -----------------------------
// Helpers
// -----------------------------
function setMouseFromEvent(e) {
const rect = renderer.domElement.getBoundingClientRect();
mouseNDC.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
mouseNDC.y = -(((e.clientY - rect.top) / rect.height) * 2 - 1);
}
function snapValue(v, step) {
return Math.round(v / step) * step;
}
function raycastGround(e) {
setMouseFromEvent(e);
raycaster.setFromCamera(mouseNDC, camera);
const hits = raycaster.intersectObject(ground, false);
if (!hits.length) {
console.log("raycastGround: No ground hit! Camera:", currentView, "NDC:", mouseNDC);
return null;
}
const p = hits[0].point.clone();
p.y = 0;
// Grid snap first
if (snapEl?.checked) {
const s = Math.max(1, Number(snapSizeEl?.value) || 10);
p.x = snapValue(p.x, s);
p.z = snapValue(p.z, s);
}
// Object snap second (corners/mids)
const res = snapToNearestObjectPoint(p.x, p.z);
p.x = res.x;
p.z = res.z;
console.log(`raycastGround: Hit at (${Math.round(p.x)}, ${Math.round(p.z)}) View: ${currentView}`);
return p;
}
function raycastObjects(e) {
setMouseFromEvent(e);
raycaster.setFromCamera(mouseNDC, camera);
const meshes = objects.map(o => o.mesh);
return raycaster.intersectObjects(meshes, false);
}
function dimsFromStartEnd(a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
return {
dx, dz,
len: Math.abs(dx),
wid: Math.abs(dz),
sx: Math.sign(dx) || 1,
sz: Math.sign(dz) || 1
};
}
function updatePreviewRect(a, b) {
const { dx, dz } = dimsFromStartEnd(a, b);
const p1 = new THREE.Vector3(a.x, 0, a.z);
const p2 = new THREE.Vector3(a.x + dx, 0, a.z);
const p3 = new THREE.Vector3(a.x + dx, 0, a.z + dz);
const p4 = new THREE.Vector3(a.x, 0, a.z + dz);
const verts = [
p1.x, p1.y, p1.z,
p2.x, p2.y, p2.z,
p3.x, p3.y, p3.z,
p4.x, p4.y, p4.z,
p1.x, p1.y, p1.z
];
previewLineGeom.setAttribute("position", new THREE.Float32BufferAttribute(verts, 3));
previewLineGeom.computeBoundingSphere();
previewLine.visible = true;
if (lenEl) lenEl.value = String(Math.round(Math.abs(dx)));
if (widEl) widEl.value = String(Math.round(Math.abs(dz)));
}
function getObjectById(id) {
return objects.find(o => o.id === id) || null;
}
function selectedObjects() {
return objects.filter(o => selected.has(o.id));
}
function refreshSelectionVisuals() {
for (const o of objects) {
o.mesh.material.color.setHex(selected.has(o.id) ? SELECT_COLOR : NORMAL_COLOR);
}
}
function clearSelection() {
selected.clear();
refreshSelectionVisuals();
exportQuantities();
}
function toggleSelection(id) {
if (selected.has(id)) selected.delete(id);
else selected.add(id);
refreshSelectionVisuals();
exportQuantities();
}
function setSingleSelection(id) {
selected.clear();
selected.add(id);
refreshSelectionVisuals();
const obj = getObjectById(id);
if (!obj) {
exportQuantities();
return;
}
// Populate fields based on mode
if (isWallMode() && !wallDrawing.active) {
// Wall mode: open modal with UVW
populateModalFromWall(obj);
} else if (!isWallMode() && !drawing) {
// Box mode: populate sidebar fields
populateSidebarFromBox(obj);
}
exportQuantities();
}
function populateSidebarFromBox(obj) {
const params = obj.mesh.geometry.parameters;
const width = params.width; // Length (X)
const depth = params.depth; // Width (Z)
const height = params.height; // Height (Y)
// Populate sidebar fields
if (lenEl) lenEl.value = String(Math.round(width));
if (widEl) widEl.value = String(Math.round(depth));
if (hgtEl) hgtEl.value = String(Math.round(height));
if (baseYEl && obj.meta && obj.meta.baseY != null) {
baseYEl.value = String(Math.round(obj.meta.baseY));
}
}
function populateModalFromWall(obj) {
// Get dimensions from the wall
const params = obj.mesh.geometry.parameters;
const width = params.width; // U (length along X axis)
const height = params.height; // V (height along Y axis)
const depth = params.depth; // W (thickness along Z axis)
// Check if this wall has UVW metadata
if (obj.meta && obj.meta.uvw) {
// Use stored UVW dimensions
if (dlU) dlU.value = String(Math.round(obj.meta.uvw.U));
if (dlV) dlV.value = String(Math.round(obj.meta.uvw.V));
if (dlW) dlW.value = String(Math.round(obj.meta.uvw.W));
} else {
// Fallback to geometry parameters
if (dlU) dlU.value = String(Math.round(width));
if (dlV) dlV.value = String(Math.round(height));
if (dlW) dlW.value = String(Math.round(depth));
}
// Set baseY
if (dlBaseY && obj.meta && obj.meta.baseY != null) {
dlBaseY.value = String(Math.round(obj.meta.baseY));
}
// Extract direction from rotation
const rotation = obj.mesh.rotation.y;
const uDirection = new THREE.Vector3(
Math.cos(-rotation),
0,
Math.sin(-rotation)
).normalize();
// Calculate W direction (perpendicular to U)
const wDirection = new THREE.Vector3()
.crossVectors(uDirection, new THREE.Vector3(0, 1, 0))
.normalize();
// Calculate the ORIGINAL ORIGIN (start corner) from the center
// We created the wall with: center = origin + U/2 + W/2
// So: origin = center - U/2 - W/2
const center = obj.mesh.position;
const baseY = obj.meta.baseY || 0;
const origin = new THREE.Vector3(
center.x - uDirection.x * (width / 2) - wDirection.x * (depth / 2),
baseY, // Use baseY directly
center.z - uDirection.z * (width / 2) - wDirection.z * (depth / 2)
);
// Start editing mode with the ACTUAL ORIGIN POINT
wallDrawing.active = true;
wallDrawing.step = 0; // 0 = editing mode (not creating)
wallDrawing.origin = origin; // Now this is the real start corner, not center!
wallDrawing.editingWall = obj; // Store reference to wall being edited
wallDrawing.U = { direction: uDirection, length: width };
// Clear any preview from previous drawing
clearPreview();
showDimModal();
}
function isTypingTarget(el) {
if (!el) return false;
const tag = (el.tagName || "").toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select") return true;
if (el.isContentEditable) return true;
return false;
}
function cancelDrawing() {
drawing = false;
startPt = null;
currentPt = null;
clearPreview();
hideDimModal();
clearDimModal();
cancelWallDrawing();
exportQuantities({ cancelled: true });
}
// -----------------------------
// View Switching (Orthographic views for Plan/Elevations)
// -----------------------------
function setView(view) {
currentView = view;
// Update button styles
const allButtons = [viewPlanBtn, viewFrontBtn, viewRearBtn, viewLeftBtn, viewRightBtn, view3DBtn];
allButtons.forEach(btn => {
if (btn) btn.className = 'btn secondary view-btn';
});
if (view === 'plan') {
// Plan view: Looking down (-Y direction)
camera = orthoCamera;
camera.position.set(0, 50000, 0);
camera.up.set(0, 0, -1); // Z points up in plan view
camera.lookAt(0, 0, 0); // Ensure camera is looking at origin
camera.updateProjectionMatrix(); // Update orthographic projection
controls.object = camera;
controls.target.set(0, 0, 0);
controls.enableRotate = false;
controls.enableDamping = false; // Disable damping for crisp orthographic view
// Disable all OrbitControls mouse buttons - we'll handle pan with SHIFT+LEFT
controls.mouseButtons = { LEFT: null, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: null };
if (viewPlanBtn) viewPlanBtn.className = 'btn primary view-btn';
} else if (view === 'front') {
// Front elevation: Looking from +Z towards -Z
camera = orthoCamera;
camera.position.set(0, 0, 50000);
camera.up.set(0, 1, 0); // Y points up
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
controls.object = camera;
controls.target.set(0, 0, 0);
controls.enableRotate = false;
controls.enableDamping = false; // Disable damping
controls.mouseButtons = { LEFT: null, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: null };
if (viewFrontBtn) viewFrontBtn.className = 'btn primary view-btn';
} else if (view === 'rear') {
// Rear elevation: Looking from -Z towards +Z
camera = orthoCamera;
camera.position.set(0, 0, -50000);
camera.up.set(0, 1, 0); // Y points up
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
controls.object = camera;
controls.target.set(0, 0, 0);
controls.enableRotate = false;
controls.enableDamping = false; // Disable damping
controls.mouseButtons = { LEFT: null, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: null };
if (viewRearBtn) viewRearBtn.className = 'btn primary view-btn';
} else if (view === 'left') {
// Left elevation: Looking from -X towards +X
camera = orthoCamera;
camera.position.set(-50000, 0, 0);
camera.up.set(0, 1, 0); // Y points up
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
controls.object = camera;
controls.target.set(0, 0, 0);
controls.enableRotate = false;
controls.enableDamping = false; // Disable damping
controls.mouseButtons = { LEFT: null, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: null };
if (viewLeftBtn) viewLeftBtn.className = 'btn primary view-btn';
} else if (view === 'right') {
// Right elevation: Looking from +X towards -X
camera = orthoCamera;
camera.position.set(50000, 0, 0);
camera.up.set(0, 1, 0); // Y points up
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
controls.object = camera;
controls.target.set(0, 0, 0);
controls.enableRotate = false;
controls.enableDamping = false; // Disable damping
controls.mouseButtons = { LEFT: null, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: null };
if (viewRightBtn) viewRightBtn.className = 'btn primary view-btn';
} else {
// 3D view: Perspective camera
camera = perspectiveCamera;
controls.object = camera;
controls.enableRotate = true;
controls.enableDamping = true; // Re-enable damping for 3D
// In 3D: LEFT rotates, RIGHT/MIDDLE for pan
controls.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };
if (view3DBtn) view3DBtn.className = 'btn primary view-btn';
}
controls.update();
}
// Wire up view buttons
if (viewPlanBtn) viewPlanBtn.addEventListener('click', () => setView('plan'));
if (viewFrontBtn) viewFrontBtn.addEventListener('click', () => setView('front'));
if (viewRearBtn) viewRearBtn.addEventListener('click', () => setView('rear'));
if (viewLeftBtn) viewLeftBtn.addEventListener('click', () => setView('left'));
if (viewRightBtn) viewRightBtn.addEventListener('click', () => setView('right'));
if (view3DBtn) view3DBtn.addEventListener('click', () => setView('3D'));
// Set initial view to 3D
setView('3D');
// -----------------------------
// Wall Mode (UVW Sequential Input)
// -----------------------------
function isWallMode() {
return wallModeEnabled;
}
function isSlabMode() {
return slabModeEnabled;
}
function isDrawingEnabled() {
return wallModeEnabled || slabModeEnabled;
}
function cancelWallDrawing() {
wallDrawing.active = false;
wallDrawing.step = 0;
wallDrawing.origin = null;
wallDrawing.U = null;
wallDrawing.V = null;
wallDrawing.W = null;
wallDrawing.currentMousePt = null;
wallDrawing.editingWall = null; // Clear editing reference
clearPreview();
}
function startWallDrawing(groundPoint) {
if (!isWallMode()) return false;
// Apply object snapping to start point
const snapped = snapToNearestObjectPoint(groundPoint.x, groundPoint.z);
const origin = new THREE.Vector3(snapped.x, groundPoint.y, snapped.z);
wallDrawing.active = true;
wallDrawing.step = 1;
wallDrawing.origin = origin;
wallDrawing.currentMousePt = origin.clone();
// Set up initial U direction (will update as mouse moves)
wallDrawing.U = { direction: new THREE.Vector3(1, 0, 0), length: 0 };
showDimModal();
// Set default values for V and W immediately
const defaultV = Number(hgtEl?.value) || 2700;
const defaultW = 230;
if (dlV) dlV.value = String(defaultV);
if (dlW) dlW.value = String(defaultW);
// Don't auto-focus - let user draw freely
exportQuantities({ wall_drawing_started: true });
return true;
}
function updateWallDrawingStep1_U(mousePoint) {
if (!wallDrawing.active || wallDrawing.step !== 1) return;
// Apply object snapping to mouse point
const snapped = snapToNearestObjectPoint(mousePoint.x, mousePoint.z);
const snappedPoint = new THREE.Vector3(snapped.x, mousePoint.y, snapped.z);
wallDrawing.currentMousePt = snappedPoint;
// Calculate U direction and length from origin to snapped mouse point
const delta = snappedPoint.clone().sub(wallDrawing.origin);
delta.y = 0; // Keep in horizontal plane
const length = delta.length();
if (length < 1) return; // Too small to show direction
let direction = delta.clone().normalize();
// Apply angle snapping if enabled
if (angleSnapEl?.checked) {
direction = snapAngle(direction);
}
// Apply custom angle if specified
if (customAngleEl?.value) {
const customDeg = Number(customAngleEl.value);
if (!isNaN(customDeg)) {
const rad = (customDeg * Math.PI) / 180;
direction = new THREE.Vector3(Math.cos(rad), 0, Math.sin(rad)).normalize();
}
}
// Update temporary U
wallDrawing.U = { direction, length };
// Update modal U field if not manually set
if (dlU && dlU !== document.activeElement) {
// Always update if field is empty OR user hasn't manually typed
if (dlU.value === "" || !uvwManual.U) {
dlU.value = String(Math.round(length));
}
}
// Draw preview line
updateWallPreview();