-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArk_Simulator.html
More file actions
1257 lines (1085 loc) · 42.2 KB
/
Copy pathArk_Simulator.html
File metadata and controls
1257 lines (1085 loc) · 42.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
<title>🚢 Arkstorm: Rescue & Repair (Playable Reset)</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#000;font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial}
canvas{display:block}
:root{
--bg: rgba(18,20,26,.92);
--line: rgba(255,255,255,.12);
--txt: rgba(255,255,255,.92);
--muted: rgba(255,255,255,.66);
--accent:#61dafb;
--ok:#46d37e;
--warn:#ff5a5a;
--btn:#3e87ff;
--btn2:#2f6bbf;
}
#hud{
position:absolute;top:10px;left:10px;width:340px;max-height:calc(100vh - 20px);
overflow:auto;background:var(--bg);color:var(--txt);
border:1px solid var(--line);border-radius:14px;padding:12px;box-shadow:0 16px 44px rgba(0,0,0,.45);
pointer-events:auto;display:flex;flex-direction:column;gap:10px;
}
#hud h3{margin:0;color:var(--accent);letter-spacing:.2px;font-size:16px}
.row{display:flex;gap:8px;align-items:center}
.row>*{flex:1}
.mini{font-size:12px;color:var(--muted);line-height:1.25}
hr{border:none;border-top:1px solid var(--line);margin:6px 0}
button{
background:var(--btn);border:none;color:#fff;padding:10px 10px;border-radius:12px;cursor:pointer;
font-weight:800;letter-spacing:.2px;transition:transform .06s, background .2s, opacity .2s;
}
button:hover{background:var(--btn2)}
button:active{transform:translateY(1px)}
button.secondary{background:rgba(255,255,255,.10)}
button.secondary:hover{background:rgba(255,255,255,.16)}
button.ok{background:var(--ok)}
button.danger{background:var(--warn)}
select,input{
width:100%;padding:9px 10px;border-radius:12px;border:1px solid var(--line);
outline:none;background:rgba(255,255,255,.06);color:var(--txt);
}
#crosshair{
position:absolute;top:50%;left:50%;width:10px;height:10px;border-radius:50%;
border:2px solid rgba(255,255,255,.55);transform:translate(-50%,-50%);display:none;pointer-events:none;
}
#toast{
position:absolute;top:10px;right:10px;max-width:44vw;
background:rgba(0,0,0,.55);color:rgba(255,255,255,.92);
border:1px solid rgba(255,255,255,.12);border-radius:14px;padding:10px 12px;font-size:12px;
display:none;pointer-events:none;box-shadow:0 16px 44px rgba(0,0,0,.35);
}
#bar{
height:10px;border-radius:999px;background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.12);overflow:hidden
}
#bar>div{height:100%;width:0%;}
#touchHUD{position:absolute;inset:0;pointer-events:none;display:none}
.stick{
position:absolute;bottom:16px;width:140px;height:140px;border-radius:50%;
border:2px solid rgba(255,255,255,.18);background:rgba(0,0,0,.12);
pointer-events:auto;touch-action:none;
}
#stickMove{left:16px}
#stickLook{right:16px}
.nub{
position:absolute;left:50%;top:50%;width:54px;height:54px;border-radius:50%;
transform:translate(-50%,-50%);
border:2px solid rgba(255,255,255,.22);background:rgba(255,255,255,.06);
}
#jumpBtn{
position:absolute;right:16px;bottom:170px;width:140px;height:54px;border-radius:16px;
border:1px solid rgba(255,255,255,.18);background:rgba(0,0,0,.22);color:rgba(255,255,255,.92);
font-weight:900;pointer-events:auto;touch-action:none;
}
#err{
position:absolute;inset:0;display:none;align-items:center;justify-content:center;
color:#fff;background:#000;padding:30px;text-align:center
}
#err code{display:block;margin-top:10px;color:#9ff}
</style>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
}
}
</script>
</head>
<body>
<div id="crosshair"></div>
<div id="toast"></div>
<div id="err">
<div>
<h2>Couldn’t load Three.js modules.</h2>
<p>This usually means a network/CSP issue loading from jsDelivr.</p>
<p>Try a different network, or download three.js locally.</p>
<code>(Open DevTools → Console for the exact error)</code>
</div>
</div>
<div id="hud">
<h3>🚢 Arkstorm: Rescue & Repair</h3>
<div class="mini">
<b>Goal:</b> collect <b id="goalSup">8</b> supply crates 📦 (earn planks) and patch all leaks 🔧 before water rises.
</div>
<div class="row">
<button id="btnPlay" class="ok">Enter Play</button>
<button id="btnBuild" class="secondary">Build Mode</button>
</div>
<div class="row">
<button id="btnReset" class="danger">Restart</button>
<button id="btnTips" class="secondary">Controls</button>
</div>
<hr />
<div class="row">
<div class="mini"><b>Supplies:</b> <span id="supCount">0</span>/<span id="supGoal2">8</span> 📦</div>
<div class="mini" style="text-align:right"><b>Planks:</b> <span id="planks">0</span> 🪵</div>
</div>
<div class="mini"><b>Leaks:</b> <span id="leaksLeft">0</span> 🔧</div>
<div id="bar"><div id="waterFill"></div></div>
<div class="mini">Water Level: <span id="waterPct">0%</span> 🌊</div>
<hr />
<div id="buildPanel" style="display:none">
<div class="mini"><b>Build:</b> place pieces using planks. Snap + rotate. Remove costs nothing.</div>
<label class="mini">Piece</label>
<select id="piece">
<option value="floor">Floor (2 planks)</option>
<option value="wall">Wall (2 planks)</option>
<option value="ramp">Ramp (3 planks)</option>
<option value="patch">Patch Plate (1 plank)</option>
<option value="door">Door (3 planks)</option>
</select>
<label class="mini">Grid Snap</label>
<select id="grid">
<option value="0.5">0.5</option>
<option value="1" selected>1</option>
<option value="2">2</option>
</select>
<div class="row">
<button id="rotL" class="secondary">⟲ Q</button>
<button id="rotR" class="secondary">⟳ E</button>
<button id="remove" class="secondary">Remove (X)</button>
</div>
<div class="mini">Click to place. Hover shows ghost. Place on decks / blocks.</div>
</div>
<div id="tips" class="mini" style="display:none">
<b>Play:</b> WASD move • Mouse look • Space jump • Shift sprint • E open door • F patch leak<br/>
<b>Build:</b> Click place • Q/E rotate • X remove • ESC exit modes<br/>
<b>Mobile:</b> Left stick move • Right stick look • Jump button
</div>
</div>
<div id="touchHUD">
<div id="stickMove" class="stick"><div class="nub" id="nubMove"></div></div>
<div id="stickLook" class="stick"><div class="nub" id="nubLook"></div></div>
<button id="jumpBtn">JUMP</button>
</div>
<script type="module">
let THREE, OrbitControls, PointerLockControls, Octree, Capsule;
try{
THREE = await import("three");
({ OrbitControls } = await import("three/addons/controls/OrbitControls.js"));
({ PointerLockControls } = await import("three/addons/controls/PointerLockControls.js"));
({ Octree } = await import("three/addons/math/Octree.js"));
({ Capsule } = await import("three/addons/math/Capsule.js"));
}catch(err){
console.error(err);
document.getElementById("err").style.display = "flex";
throw err;
}
const $ = (id)=>document.getElementById(id);
const isTouch = matchMedia("(pointer: coarse)").matches || ("ontouchstart" in window);
// ---------- Toast ----------
let toastT=null;
function toast(msg, ms=1200){
$("toast").textContent = msg;
$("toast").style.display = "block";
clearTimeout(toastT);
toastT = setTimeout(()=> $("toast").style.display="none", ms);
}
// ---------- Renderer / Scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x89c7ff);
scene.fog = new THREE.Fog(0x89c7ff, 40, 520);
const renderer = new THREE.WebGLRenderer({ antialias:true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(65, innerWidth/innerHeight, 0.1, 1600);
camera.position.set(55, 28, 55);
// Lights
scene.add(new THREE.HemisphereLight(0xffffff, 0x244055, 0.9));
const sun = new THREE.DirectionalLight(0xffffff, 1.35);
sun.position.set(100, 160, 80);
sun.castShadow = true;
sun.shadow.mapSize.set(2048,2048);
sun.shadow.camera.near = 20;
sun.shadow.camera.far = 520;
sun.shadow.camera.left = -200;
sun.shadow.camera.right = 200;
sun.shadow.camera.top = 200;
sun.shadow.camera.bottom = -200;
scene.add(sun);
// Controls: Orbit for build/overview, PointerLock for play
const orbit = new OrbitControls(camera, renderer.domElement);
orbit.enableDamping = true;
orbit.target.set(0, 6, 0);
const plc = new PointerLockControls(camera, document.body);
// ---------- Materials ----------
const MAT = {
wood: new THREE.MeshStandardMaterial({ color:0x7a5535, roughness:0.82, metalness:0.05 }),
wood2:new THREE.MeshStandardMaterial({ color:0xcda779, roughness:0.55, metalness:0.05 }),
metal:new THREE.MeshStandardMaterial({ color:0xb87333, roughness:0.35, metalness:0.7 }),
glass:new THREE.MeshPhysicalMaterial({ color:0xffffff, transmission:0.9, roughness:0.02, thickness:0.6, transparent:true }),
leak :new THREE.MeshStandardMaterial({ color:0x00ffd4, emissive:0x00ffd4, emissiveIntensity:1.6, roughness:0.2 }),
crate:new THREE.MeshStandardMaterial({ color:0x3e87ff, roughness:0.35, metalness:0.2 }),
ghost:new THREE.MeshStandardMaterial({ color:0xffffff, transparent:true, opacity:0.28, roughness:0.5, metalness:0.0 })
};
// ---------- World ----------
const world = new THREE.Group(); scene.add(world);
const ark = new THREE.Group(); world.add(ark);
const staticColliders = new THREE.Group(); // invisible collider meshes
world.add(staticColliders);
const buildables = []; // placed blocks in build mode
const interactables = []; // doors, crates, leak markers, etc.
const worldOctree = new Octree();
const ARK_R = 28;
const MAX_R = ARK_R * 0.95;
// Water plane (animated)
const waterGeo = new THREE.PlaneGeometry(900, 900, 140, 140);
const waterMat = new THREE.MeshStandardMaterial({ color:0x003f66, roughness:0.25, metalness:0.7, transparent:true, opacity:0.86 });
const water = new THREE.Mesh(waterGeo, waterMat);
water.rotation.x = -Math.PI/2;
water.position.y = -6.2;
water.receiveShadow = true;
scene.add(water);
const waterBase = new Float32Array(waterGeo.attributes.position.array.length);
waterBase.set(waterGeo.attributes.position.array);
// Decorative sky birds
const birds = new THREE.Group(); scene.add(birds);
for(let i=0;i<22;i++){
const m = new THREE.Mesh(new THREE.SphereGeometry(0.2, 10, 8), new THREE.MeshStandardMaterial({ color:0xffffff }));
m.position.set((Math.random()-0.5)*240, 40+Math.random()*40, (Math.random()-0.5)*240);
birds.add(m);
}
function addColliderBox(pos, size, rotY=0){
const c = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
new THREE.MeshBasicMaterial({ visible:false })
);
c.position.copy(pos);
c.rotation.y = rotY;
c.userData.isCollider = true;
staticColliders.add(c);
return c;
}
function addRailRing(y, r){
// visible rail
const rail = new THREE.Mesh(
new THREE.TorusGeometry(r, 0.18, 10, 96),
MAT.metal.clone()
);
rail.position.y = y + 1.0;
rail.rotation.x = Math.PI/2;
rail.castShadow = true;
ark.add(rail);
// invisible wall segments (keeps player from falling off)
const n=32;
for(let i=0;i<n;i++){
const a=(i/n)*Math.PI*2;
const segLen=(2*Math.PI*r)/n;
const p = new THREE.Vector3(Math.cos(a)*r, y+1.5, Math.sin(a)*r);
addColliderBox(p, new THREE.Vector3(segLen*0.92, 2.6, 0.4), -a);
}
}
function addDeck(y, r, thickness=0.7){
const deck = new THREE.Mesh(
new THREE.CylinderGeometry(r, r, thickness, 48, 1, false),
MAT.wood2.clone()
);
deck.position.y = y;
deck.receiveShadow = true;
deck.castShadow = false;
deck.userData.isSurface = true;
ark.add(deck);
// collider (slightly thicker)
addColliderBox(new THREE.Vector3(0, y, 0), new THREE.Vector3(r*2.02, thickness+0.35, r*2.02), 0);
addRailRing(y, r);
return deck;
}
function addRamp(y0, y1, r, ang){
const len = 9.8;
const rise = y1 - y0;
const slope = Math.atan2(rise, len);
const ramp = new THREE.Mesh(
new THREE.BoxGeometry(len, 0.6, 2.2),
MAT.wood2.clone()
);
const cx = Math.cos(ang)*r*0.22;
const cz = Math.sin(ang)*r*0.22;
ramp.position.set(cx, (y0+y1)/2 + 0.15, cz);
ramp.rotation.y = -ang;
ramp.rotation.z = -slope;
ramp.castShadow = true;
ramp.receiveShadow = true;
ark.add(ramp);
// collider
const col = new THREE.Mesh(ramp.geometry, new THREE.MeshBasicMaterial({visible:false}));
col.position.copy(ramp.position);
col.rotation.copy(ramp.rotation);
staticColliders.add(col);
}
function makeDoor(x,z,y, rotY){
// door group with pivot + collider when closed
const g = new THREE.Group();
g.position.set(x, y, z);
g.rotation.y = rotY;
g.userData.isDoor = true;
g.userData.open01 = 0;
const frame = new THREE.Mesh(new THREE.BoxGeometry(1.35, 2.35, 0.28), MAT.wood.clone());
frame.castShadow = frame.receiveShadow = true;
g.add(frame);
const pivot = new THREE.Group();
pivot.position.x = -0.45;
g.add(pivot);
const leaf = new THREE.Mesh(new THREE.BoxGeometry(0.9, 2.05, 0.18), MAT.wood2.clone());
leaf.position.x = 0.45;
leaf.position.y = -0.05;
leaf.castShadow = leaf.receiveShadow = true;
pivot.add(leaf);
const col = new THREE.Mesh(new THREE.BoxGeometry(0.9, 2.05, 0.35), new THREE.MeshBasicMaterial({visible:false}));
col.position.copy(leaf.position);
col.userData.doorCollider = true;
pivot.add(col);
staticColliders.add(col);
g.userData.pivot = pivot;
g.userData.collider = col;
ark.add(g);
interactables.push(g);
return g;
}
function buildArk(){
// hull (stylized capsule-like)
const hull = new THREE.Mesh(new THREE.CapsuleGeometry(ARK_R*0.95, ARK_R*1.05, 10, 28), MAT.wood.clone());
hull.scale.set(1.05, 0.42, 1.05);
hull.position.y = -10.5;
hull.castShadow = true;
hull.receiveShadow = true;
ark.add(hull);
// inner posts
for(let i=0;i<10;i++){
const p = new THREE.Mesh(new THREE.CylinderGeometry(0.35,0.45, 18, 12), MAT.wood2.clone());
const a = (i/10)*Math.PI*2;
p.position.set(Math.cos(a)*5.8, -2.2, Math.sin(a)*5.8);
p.castShadow = true;
p.receiveShadow = true;
ark.add(p);
addColliderBox(p.position.clone(), new THREE.Vector3(1.1, 18.2, 1.1));
}
const deckLow = addDeck(-10.0, ARK_R*0.70);
const deckMid = addDeck(-4.7, ARK_R*0.82);
const deckTop = addDeck( 0.0, ARK_R*0.92);
// ramps
addRamp(deckLow.position.y+0.35, deckMid.position.y+0.35, ARK_R, 0.3);
addRamp(deckMid.position.y+0.35, deckTop.position.y+0.35, ARK_R, -1.2);
// roof / canopy
const roof = new THREE.Mesh(new THREE.ConeGeometry(ARK_R*1.02, 8.2, 72, 1, true), MAT.metal.clone());
roof.position.y = 6.3;
roof.castShadow = true;
ark.add(roof);
const glassBand = new THREE.Mesh(new THREE.CylinderGeometry(ARK_R*0.98, ARK_R*0.98, 3.6, 64, 1, true), MAT.glass.clone());
glassBand.position.y = 3.1;
ark.add(glassBand);
// doors on mid deck
makeDoor( 6.5, 0.0, -3.5, Math.PI/2);
makeDoor(-6.5, 0.0, -3.5, -Math.PI/2);
// “safe invisible ceiling” (keeps physics stable)
addColliderBox(new THREE.Vector3(0, 14, 0), new THREE.Vector3(ARK_R*2.2, 1, ARK_R*2.2));
}
// ---------- Gameplay Objects ----------
const supplies = [];
const leaks = [];
let suppliesCollected = 0;
let suppliesGoal = 8;
let waterLevel01 = 0; // 0..1 lose at 1
let planks = 0;
function uiSync(){
$("supCount").textContent = String(suppliesCollected);
$("supGoal2").textContent = String(suppliesGoal);
$("goalSup").textContent = String(suppliesGoal);
$("planks").textContent = String(planks);
$("leaksLeft").textContent = String(leaks.filter(l=>!l.userData.patched).length);
const pct = Math.round(waterLevel01*100);
$("waterPct").textContent = pct + "%";
$("waterFill").style.width = pct + "%";
$("waterFill").style.background = waterLevel01 < 0.65 ? "rgba(70,211,126,.95)" : (waterLevel01 < 0.85 ? "rgba(255,200,90,.95)" : "rgba(255,90,90,.95)");
}
function spawnSupplyCrate(pos){
const g = new THREE.Group();
const box = new THREE.Mesh(new THREE.BoxGeometry(1.4,1.1,1.4), MAT.crate.clone());
box.castShadow = true; box.receiveShadow = true;
g.add(box);
const ring = new THREE.Mesh(new THREE.TorusGeometry(1.2, 0.08, 10, 48), new THREE.MeshStandardMaterial({ color:0xffffff, emissive:0x61dafb, emissiveIntensity:1.2 }));
ring.rotation.x = Math.PI/2;
ring.position.y = 0.9;
g.add(ring);
g.position.copy(pos);
g.userData.isSupply = true;
g.userData.bob = Math.random()*Math.PI*2;
scene.add(g);
supplies.push(g);
interactables.push(g);
}
function spawnLeak(pos){
const l = new THREE.Group();
const disc = new THREE.Mesh(new THREE.CylinderGeometry(0.7,0.7,0.08, 22), MAT.leak.clone());
disc.castShadow = false; disc.receiveShadow = false;
l.add(disc);
const beam = new THREE.Mesh(new THREE.CylinderGeometry(0.12,0.12,2.6, 14), new THREE.MeshStandardMaterial({ color:0x00ffd4, emissive:0x00ffd4, emissiveIntensity:1.7, transparent:true, opacity:0.55 }));
beam.position.y = 1.3;
l.add(beam);
l.position.copy(pos);
l.userData.isLeak = true;
l.userData.patched = false;
scene.add(l);
leaks.push(l);
interactables.push(l);
}
function clearGameplay(){
supplies.forEach(s=> scene.remove(s));
leaks.forEach(l=> scene.remove(l));
supplies.length = 0;
leaks.length = 0;
interactables.length = 0;
buildables.length = 0;
// keep static colliders (ark) intact, but remove any buildable colliders by recreating ark collision set later
}
// ---------- Buildables ----------
function costForPiece(type){
if(type==="floor") return 2;
if(type==="wall") return 2;
if(type==="ramp") return 3;
if(type==="patch") return 1;
if(type==="door") return 3;
return 2;
}
function makeBuildable(type, pos, rotY){
const g = new THREE.Group();
g.userData.isBuildable = true;
g.userData.type = type;
g.position.copy(pos);
g.rotation.y = rotY;
let mesh, collider;
if(type==="floor"){
mesh = new THREE.Mesh(new THREE.BoxGeometry(4,0.55,4), MAT.wood2.clone());
}else if(type==="wall"){
mesh = new THREE.Mesh(new THREE.BoxGeometry(4,2.6,0.45), MAT.wood.clone());
mesh.position.y = 1.0;
}else if(type==="ramp"){
mesh = new THREE.Mesh(new THREE.BoxGeometry(5.0,0.55,3.2), MAT.wood2.clone());
mesh.rotation.x = -0.35;
mesh.position.y = 0.2;
}else if(type==="patch"){
mesh = new THREE.Mesh(new THREE.CylinderGeometry(1.0,1.0,0.12, 24), new THREE.MeshStandardMaterial({ color:0xdddddd, roughness:0.3, metalness:0.85 }));
mesh.position.y = 0.06;
}else if(type==="door"){
// place a real interactable door
const d = new THREE.Group();
d.userData.isDoor = true;
d.userData.open01 = 0;
const frame = new THREE.Mesh(new THREE.BoxGeometry(1.35, 2.35, 0.28), MAT.wood.clone());
frame.castShadow = frame.receiveShadow = true;
d.add(frame);
const pivot = new THREE.Group();
pivot.position.x = -0.45;
d.add(pivot);
const leaf = new THREE.Mesh(new THREE.BoxGeometry(0.9, 2.05, 0.18), MAT.wood2.clone());
leaf.position.x = 0.45;
leaf.position.y = -0.05;
leaf.castShadow = leaf.receiveShadow = true;
pivot.add(leaf);
const col = new THREE.Mesh(new THREE.BoxGeometry(0.9,2.05,0.35), new THREE.MeshBasicMaterial({visible:false}));
col.position.copy(leaf.position);
col.userData.doorCollider = true;
pivot.add(col);
staticColliders.add(col);
d.userData.pivot = pivot;
d.userData.collider = col;
d.position.copy(pos);
d.rotation.y = rotY;
ark.add(d);
interactables.push(d);
scheduleRebuild();
toast("Door placed");
return d;
}
mesh.castShadow = true;
mesh.receiveShadow = true;
g.add(mesh);
// collider = copy of mesh bounds (simple box/cyl)
if(type==="patch"){
collider = new THREE.Mesh(new THREE.CylinderGeometry(1.0,1.0,0.22, 18), new THREE.MeshBasicMaterial({visible:false}));
collider.position.y = 0.1;
}else{
collider = new THREE.Mesh(mesh.geometry, new THREE.MeshBasicMaterial({visible:false}));
collider.position.copy(mesh.position);
collider.rotation.copy(mesh.rotation);
}
collider.userData.isCollider = true;
g.add(collider);
staticColliders.add(collider);
ark.add(g);
buildables.push(g);
scheduleRebuild();
return g;
}
// ---------- Physics (Player) ----------
const playerCollider = new Capsule(
new THREE.Vector3(0, 0.35, 0),
new THREE.Vector3(0, 1.65, 0),
0.35
);
const playerVelocity = new THREE.Vector3();
const playerDir = new THREE.Vector3();
let playerOnFloor = false;
const GRAVITY = 28;
const WALK_SPEED = 8.0;
const SPRINT_MULT = 1.55;
const JUMP_V = 10.5;
const SAFE_SPAWNS = [
new THREE.Vector3(0, 1.8, 0),
new THREE.Vector3(0, -3.2, 0),
new THREE.Vector3(0, -8.7, 0)
];
let lastSafe = SAFE_SPAWNS[0].clone();
let rescueCD = 0;
function teleportTo(v){
const h = playerCollider.end.y - playerCollider.start.y;
playerCollider.start.set(v.x, v.y - (h-0.35), v.z);
playerCollider.end.set(v.x, v.y, v.z);
playerVelocity.set(0,0,0);
camera.position.copy(playerCollider.end);
}
function getForward(){
camera.getWorldDirection(playerDir);
playerDir.y = 0; playerDir.normalize();
return playerDir;
}
function getSide(){
camera.getWorldDirection(playerDir);
playerDir.y = 0; playerDir.normalize();
playerDir.cross(camera.up);
return playerDir;
}
function playerCollisions(){
const res = worldOctree.capsuleIntersect(playerCollider);
playerOnFloor = false;
if(res){
playerOnFloor = res.normal.y > 0;
if(!playerOnFloor){
playerVelocity.addScaledVector(res.normal, -res.normal.dot(playerVelocity));
}
playerCollider.translate(res.normal.multiplyScalar(res.depth));
}
}
function clampAndRescue(dt){
rescueCD = Math.max(0, rescueCD - dt);
const p = playerCollider.end;
const r = Math.hypot(p.x, p.z);
if(r > MAX_R){
const k = MAX_R / r;
p.x *= k; p.z *= k;
const h = playerCollider.end.y - playerCollider.start.y;
playerCollider.start.set(p.x, p.y - h, p.z);
}
if(playerOnFloor && p.y > -15 && p.y < 14 && r < MAX_R-1.2){
lastSafe.copy(p);
}
const out = (p.y < -20) || (p.y > 20) || (r > MAX_R + 8);
const stuck = (!playerOnFloor && Math.abs(playerVelocity.y) < 0.05 && p.y < -14.6);
if((out || stuck) && rescueCD<=0){
rescueCD = 1.2;
teleportTo(lastSafe.clone());
toast("Rescued 🛟");
}
}
let kF=false,kB=false,kL=false,kR=false,kShift=false;
function updatePlayer(dt){
if(!playerOnFloor) playerVelocity.y -= GRAVITY*dt;
else playerVelocity.y = Math.max(0, playerVelocity.y);
// friction
const damping = Math.exp(-6*dt)-1;
playerVelocity.addScaledVector(playerVelocity, damping);
const speed = WALK_SPEED*(kShift?SPRINT_MULT:1);
const move = new THREE.Vector3();
if(kF) move.add(getForward());
if(kB) move.add(getForward().multiplyScalar(-1));
if(kL) move.add(getSide().multiplyScalar(-1));
if(kR) move.add(getSide());
if(move.lengthSq()>0){
move.normalize();
playerVelocity.addScaledVector(move, speed*dt*18);
}
playerCollider.translate(playerVelocity.clone().multiplyScalar(dt));
playerCollisions();
clampAndRescue(dt);
camera.position.copy(playerCollider.end);
}
// ---------- Touch Controls ----------
const stickState = {
move:{id:null,cx:0,cy:0,x:0,y:0},
look:{id:null,cx:0,cy:0,x:0,y:0},
};
function bindStick(el, nub, st){
const clamp=(v,m)=>Math.max(-m,Math.min(m,v));
const rect=()=>el.getBoundingClientRect();
el.addEventListener("pointerdown",(e)=>{
el.setPointerCapture(e.pointerId);
const r=rect();
st.id=e.pointerId;
st.cx=r.left+r.width/2; st.cy=r.top+r.height/2;
st.x=0; st.y=0;
});
el.addEventListener("pointermove",(e)=>{
if(st.id!==e.pointerId) return;
const dx=e.clientX-st.cx, dy=e.clientY-st.cy;
const max=44;
st.x=clamp(dx,max)/max; st.y=clamp(dy,max)/max;
nub.style.transform = "translate("+(st.x*44-27)+"px,"+(st.y*44-27)+"px)";
});
const up=(e)=>{
if(st.id!==e.pointerId) return;
st.id=null; st.x=0; st.y=0;
nub.style.transform="translate(-50%,-50%)";
};
el.addEventListener("pointerup",up);
el.addEventListener("pointercancel",up);
}
bindStick($("stickMove"), $("nubMove"), stickState.move);
bindStick($("stickLook"), $("nubLook"), stickState.look);
$("jumpBtn").addEventListener("pointerdown", ()=>{
if(mode==="play" && playerOnFloor) playerVelocity.y = JUMP_V;
});
let touchYaw=0, touchPitch=0;
// ---------- Mode / UI ----------
let mode = "build"; // "build" or "play"
function setMode(m){
mode = m;
const inPlay = (mode==="play");
$("crosshair").style.display = inPlay ? "block" : "none";
$("buildPanel").style.display = inPlay ? "none" : "block";
$("btnBuild").classList.toggle("ok", !inPlay);
$("btnBuild").classList.toggle("secondary", inPlay);
$("btnPlay").classList.toggle("ok", inPlay);
$("btnPlay").classList.toggle("secondary", !inPlay);
orbit.enabled = !inPlay;
if(inPlay){
$("touchHUD").style.display = isTouch ? "block" : "none";
if(!isTouch) plc.lock();
toast("Play ON 🎮");
}else{
if(!isTouch) plc.unlock();
$("touchHUD").style.display = "none";
toast("Build ON 🧱");
}
}
$("btnPlay").onclick = ()=> setMode("play");
$("btnBuild").onclick = ()=> setMode("build");
plc.addEventListener("unlock", ()=>{
if(mode==="play" && !isTouch) setMode("build");
});
$("btnTips").onclick = ()=>{
const show = $("tips").style.display !== "block";
$("tips").style.display = show ? "block" : "none";
};
// ---------- Raycasting / Interactions ----------
const ray = new THREE.Raycaster();
const ndc = new THREE.Vector2();
function centerRaycast(maxDist=3.0){
ndc.set(0,0);
ray.setFromCamera(ndc, camera);
const hits = ray.intersectObjects(interactables, true);
if(!hits.length) return null;
const h = hits[0];
if(h.distance > maxDist) return null;
return h.object;
}
function tryOpenDoor(){
const obj = centerRaycast(2.4);
if(!obj) return false;
const door = obj.userData.isDoor ? obj : obj.parent?.userData?.isDoor ? obj.parent : obj.parent?.parent?.userData?.isDoor ? obj.parent.parent : null;
if(!door) return false;
door.userData.open01 = door.userData.open01 > 0.5 ? 0 : 1;
toast(door.userData.open01>0.5 ? "Door opened 🚪" : "Door closed 🚪");
scheduleRebuild();
return true;
}
function tryCollectSupply(){
for(const s of supplies){
const p = playerCollider.end;
if(p.distanceTo(s.position) < 1.35){
suppliesCollected++;
planks += 3;
scene.remove(s);
const idx = supplies.indexOf(s);
if(idx>=0) supplies.splice(idx,1);
const ii = interactables.indexOf(s);
if(ii>=0) interactables.splice(ii,1);
toast("+3 planks 🪵");
uiSync();
return true;
}
}
return false;
}
function tryPatchLeak(){
// Patch with F when close (or with Patch Plate placed in build mode)
const p = playerCollider.end;
const unpatched = leaks.find(l => !l.userData.patched && p.distanceTo(l.position) < 1.7);
if(!unpatched) return false;
if(planks < 1){
toast("Need 1 plank 🪵");
return true;
}
planks -= 1;
unpatched.userData.patched = true;
unpatched.children[0].material = new THREE.MeshStandardMaterial({ color:0x7dff7d, emissive:0x2aff2a, emissiveIntensity:1.2, roughness:0.4 });
toast("Leak patched 🔧");
uiSync();
return true;
}
// ---------- Build Mode (Ghost + Place/Remove) ----------
const surfaces = []; // decks + buildables that act as surfaces
function addSurface(obj){ surfaces.push(obj); }
let ghost = new THREE.Mesh(new THREE.BoxGeometry(4,0.55,4), MAT.ghost.clone());
ghost.visible = false;
ghost.castShadow = false;
scene.add(ghost);
let ghostRotY = 0;
function setGhostGeometry(type){
if(type==="floor") ghost.geometry = new THREE.BoxGeometry(4,0.55,4);
if(type==="wall") ghost.geometry = new THREE.BoxGeometry(4,2.6,0.45);
if(type==="ramp") ghost.geometry = new THREE.BoxGeometry(5.0,0.55,3.2);
if(type==="patch") ghost.geometry = new THREE.CylinderGeometry(1.0,1.0,0.12, 24);
if(type==="door") ghost.geometry = new THREE.BoxGeometry(1.35,2.35,0.28);
}
function snapVec3(v, g){
v.x = Math.round(v.x/g)*g;
v.y = Math.round(v.y/g)*g;
v.z = Math.round(v.z/g)*g;
}
function updateGhostFromPointer(clientX, clientY){
if(mode!=="build") { ghost.visible=false; return; }
ndc.x = (clientX/innerWidth)*2 - 1;
ndc.y = -(clientY/innerHeight)*2 + 1;
ray.setFromCamera(ndc, camera);
const hits = ray.intersectObjects(surfaces, true);
if(!hits.length){ ghost.visible=false; return; }
const h = hits[0];
const type = $("piece").value;
setGhostGeometry(type);
const g = parseFloat($("grid").value);
const p = h.point.clone();
// hover height offset based on type
if(type==="wall"){ p.y += 1.3; }
else if(type==="door"){ p.y += 1.15; }
else if(type==="patch"){ p.y += 0.07; }
else { p.y += 0.28; }
snapVec3(p, g);
ghost.visible = true;
ghost.position.copy(p);
ghost.rotation.set(0, ghostRotY, 0);
// ramp tilt for readability
if(type==="ramp") ghost.rotation.x = -0.35;
else ghost.rotation.x = 0;
}
function placeGhost(){
if(!ghost.visible) return;
const type = $("piece").value;
const cost = costForPiece(type);
if(planks < cost){
toast(`Need ${cost} planks 🪵`);
return;
}
planks -= cost;
const pos = ghost.position.clone();
const obj = makeBuildable(type, pos, ghostRotY);
if(obj){
// allow placing on buildables too
addSurface(obj);
toast(`Placed ${type} (-${cost})`);
}
uiSync();
}
function removeBuildableAtPointer(clientX, clientY){
ndc.x = (clientX/innerWidth)*2 - 1;
ndc.y = -(clientY/innerHeight)*2 + 1;
ray.setFromCamera(ndc, camera);
const hits = ray.intersectObjects(buildables, true);
if(!hits.length){ toast("Nothing to remove"); return; }
const hit = hits[0].object;
const root = hit.userData.isBuildable ? hit : hit.parent?.userData?.isBuildable ? hit.parent : hit.parent?.parent?.userData?.isBuildable ? hit.parent.parent : null;
if(!root){ toast("Nothing to remove"); return; }
// remove collider child from staticColliders
root.traverse(o=>{
if(o.userData && o.userData.isCollider){
staticColliders.remove(o);
}
});
ark.remove(root);
const idx = buildables.indexOf(root);
if(idx>=0) buildables.splice(idx,1);
toast("Removed ✅");
scheduleRebuild();
}
// Pointer events
renderer.domElement.addEventListener("pointermove",(e)=>{
updateGhostFromPointer(e.clientX, e.clientY);
});
renderer.domElement.addEventListener("pointerdown",(e)=>{
if(e.target.closest("#hud")) return;
if(mode==="build"){
if($("remove").dataset.on==="1"){
removeBuildableAtPointer(e.clientX, e.clientY);
}else{
placeGhost();
}
}
});
$("rotL").onclick = ()=> { ghostRotY += Math.PI/2; toast("Rotate ⟲"); };
$("rotR").onclick = ()=> { ghostRotY -= Math.PI/2; toast("Rotate ⟳"); };
$("remove").onclick = ()=>{
const on = $("remove").dataset.on === "1";
$("remove").dataset.on = on ? "0" : "1";
$("remove").textContent = (on ? "Remove (X)" : "REMOVE: ON (X)");
toast(on ? "Remove OFF" : "Remove ON");
};
// ---------- Octree rebuild ----------
let rebuildT=null;
function rebuildOctree(){
worldOctree.clear();
worldOctree.fromGraphNode(staticColliders);
// Note: staticColliders holds all invisible colliders.
}
function scheduleRebuild(){
clearTimeout(rebuildT);
rebuildT = setTimeout(()=>{ rebuildOctree(); }, 80);
}
// ---------- Keyboard ----------
window.addEventListener("keydown",(e)=>{
if(e.key==="Escape"){
if(mode==="play") setMode("build");
$("remove").dataset.on="0";
$("remove").textContent="Remove (X)";
return;
}
if(mode==="play"){
if(e.code==="KeyW"||e.code==="ArrowUp") kF=true;
if(e.code==="KeyS"||e.code==="ArrowDown") kB=true;
if(e.code==="KeyA"||e.code==="ArrowLeft") kL=true;
if(e.code==="KeyD"||e.code==="ArrowRight") kR=true;
if(e.code==="ShiftLeft"||e.code==="ShiftRight") kShift=true;
if(e.code==="Space" && playerOnFloor) playerVelocity.y = JUMP_V;
if(e.code==="KeyE") tryOpenDoor();