File size: 34,276 Bytes
0e2a721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Three.js Forest with Orbit + Arrow Move + Lighting + Stars</title>
    <style>
        :root { color-scheme: dark; }
        html, body { height: 100%; }
        body {
            margin: 0;
            overflow: hidden;
            background: #0a0f12;
            font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji";
        }
        .ui {
            position: absolute;
            top: 12px;
            left: 12px;
            padding: 10px 12px;
            background: rgba(0,0,0,0.35);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 8px;
            backdrop-filter: blur(6px);
            -webkit-backdrop-filter: blur(6px);
            color: #cfe3d4;
            font-size: 12px;
            line-height: 1.4;
            user-select: none;
            max-width: 360px;
        }
        .ui h1 {
            margin: 0 0 6px 0;
            font-size: 14px;
            font-weight: 600;
            color: #e8f5ea;
            letter-spacing: 0.3px;
        }
        .ui .row {
            display: flex;
            align-items: center;
            gap: 8px;
            margin: 6px 0;
        }
        .ui label {
            min-width: 90px;
            color: #cde2cf;
        }
        .ui input[type=range] { width: 180px; }
        .ui .hint { opacity: 0.85; font-size: 11px; margin-top: 6px; }
        .kbd {
            display: inline-block;
            padding: 1px 6px;
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 4px;
            background: rgba(255,255,255,0.06);
            font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
            font-size: 11px;
            line-height: 16px;
        }
    </style>
</head>
<body>
    <div class="ui">
        <h1>Procedural Forest</h1>
        <div class="row">
            <label for="density">Density</label>
            <input id="density" type="range" min="50" max="1200" value="550" />
            <span id="densityVal">550</span>
        </div>
        <div class="row">
            <label for="wind">Wind</label>
            <input id="wind" type="range" min="0" max="100" value="35" />
            <span id="windVal">0.35</span>
        </div>
        <div class="row">
            <label for="size">Area</label>
            <input id="size" type="range" min="150" max="600" value="350" />
            <span id="sizeVal">350</span>
        </div>

        <h1 style="margin-top:10px;">Lighting</h1>
        <div class="row">
            <label for="sunInt">Sun Intensity</label>
            <input id="sunInt" type="range" min="0" max="2000" value="1000" />
            <span id="sunIntVal">10.00</span>
        </div>
        <div class="row">
            <label for="sunElev">Sun Elev</label>
            <input id="sunElev" type="range" min="5" max="85" value="60" />
            <span id="sunElevVal">60°</span>
        </div>
        <div class="row">
            <label for="sunAzim">Sun Azim</label>
            <input id="sunAzim" type="range" min="0" max="360" value="145" />
            <span id="sunAzimVal">145°</span>
        </div>
        <div class="row">
            <label for="hemi">Sky/Amb</label>
            <input id="hemi" type="range" min="0" max="150" value="60" />
            <span id="hemiVal">0.60</span>
        </div>

        <div class="hint">
            Orbit: Left drag • Pan: Right drag • Zoom: Wheel<br/>
            Move camera with <span class="kbd"></span><span class="kbd"></span><span class="kbd"></span><span class="kbd"></span> • Boost: <span class="kbd">Shift</span><br/>
            Tip: Click the canvas once to ensure it has focus for arrow keys.
        </div>
    </div>

    <script type="importmap">
        {
            "imports": {
                "three": "https://unpkg.com/three@0.160.0/build/three.module.js",
                "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
            }
        }
    </script>
    <script type="module">
        import * as THREE from 'three';
        import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        renderer.domElement.tabIndex = 0; // make focusable for key events
        document.body.appendChild(renderer.domElement);

        const scene = new THREE.Scene();
        scene.fog = new THREE.FogExp2(0x0d1713, 0.0022);

        // Lights
        const hemiLight = new THREE.HemisphereLight(0xbfdde3, 0x1e3222, 0.6);
        scene.add(hemiLight);

        const dirLight = new THREE.DirectionalLight(0xfff4d6, 3.0); // default x3 intensity
        dirLight.position.set(-60, 120, 40);
        dirLight.castShadow = true;
        dirLight.shadow.mapSize.set(2048, 2048);
        const cam = dirLight.shadow.camera;
        const shadowExtent = 300;
        cam.left = -shadowExtent;
        cam.right = shadowExtent;
        cam.top = shadowExtent;
        cam.bottom = -shadowExtent;
        cam.near = 10;
        cam.far = 400;
        scene.add(dirLight);

        // Hook up UI controls
        const densityEl = document.getElementById('density');
        const densityValEl = document.getElementById('densityVal');
        const windEl = document.getElementById('wind');
        const windValEl = document.getElementById('windVal');
        const sizeEl = document.getElementById('size');
        const sizeValEl = document.getElementById('sizeVal');

        const sunIntEl = document.getElementById('sunInt');
        const sunIntValEl = document.getElementById('sunIntVal');
        const sunElevEl = document.getElementById('sunElev');
        const sunElevValEl = document.getElementById('sunElevVal');
        const sunAzimEl = document.getElementById('sunAzim');
        const sunAzimValEl = document.getElementById('sunAzimVal');
        const hemiEl = document.getElementById('hemi');
        const hemiValEl = document.getElementById('hemiVal');

        // Initial UI state sync
        function setSunFromUI() {
            const intensity = Number(sunIntEl.value) / 100; // 0..20
            dirLight.intensity = intensity;
            sunIntValEl.textContent = intensity.toFixed(2);

            const elevDeg = Number(sunElevEl.value);
            const azimDeg = Number(sunAzimEl.value);
            sunElevValEl.textContent = elevDeg + '°';
            sunAzimValEl.textContent = azimDeg + '°';

            // Position the directional light based on elevation/azimuth around origin
            const elev = THREE.MathUtils.degToRad(elevDeg);
            const azim = THREE.MathUtils.degToRad(azimDeg);
            const r = 200;
            const y = Math.sin(elev) * r;
            const x = Math.cos(elev) * Math.cos(azim) * r;
            const z = Math.cos(elev) * Math.sin(azim) * r;
            dirLight.position.set(x, y, z);
            dirLight.target.position.set(0, 0, 0);
            dirLight.target.updateMatrixWorld();
        }

        function setHemiFromUI() {
            const hemiIntensity = Number(hemiEl.value) / 100; // 0..1.5
            hemiLight.intensity = hemiIntensity;
            hemiValEl.textContent = hemiIntensity.toFixed(2);
        }

        function setWindFromUI() {
            const w = Number(windEl.value) / 100;
            wind.strength = w;
            windValEl.textContent = w.toFixed(2);
            windUniforms.uStrength.value = w;
        }

        function setDensityFromUI() {
            const d = Number(densityEl.value);
            densityValEl.textContent = String(d);
            regenerateForest(d, areaSize.value);
            regenerateDecor(areaSize.value);
        }

        function setAreaFromUI() {
            const s = Number(sizeEl.value);
            areaSize.value = s;
            sizeValEl.textContent = String(s);
            regenerateForest(Number(densityEl.value), s);
            regenerateDecor(s);
        }

        sunIntEl.addEventListener('input', setSunFromUI);
        sunElevEl.addEventListener('input', setSunFromUI);
        sunAzimEl.addEventListener('input', setSunFromUI);
        hemiEl.addEventListener('input', setHemiFromUI);
        windEl.addEventListener('input', setWindFromUI);
        densityEl.addEventListener('change', setDensityFromUI);
        sizeEl.addEventListener('change', setAreaFromUI);

        // Ground
        const areaSize = { value: 350 };
        const groundSegments = 256;
        const groundGeo = new THREE.PlaneGeometry(1000, 1000, groundSegments, groundSegments);
        groundGeo.rotateX(-Math.PI / 2);
        const pos = groundGeo.attributes.position;
        const tmp = new THREE.Vector3();
        for (let i = 0; i < pos.count; i++) {
            tmp.fromBufferAttribute(pos, i);
            const nx = tmp.x * 0.01;
            const nz = tmp.z * 0.01;
            const h =
                Math.sin(nx) * Math.cos(nz) * 1.2 +
                Math.sin(nx * 0.21 + 2.7) * Math.sin(nz * 0.19 + 1.5) * 0.7 +
                Math.cos(nx * 0.07 - 1.1) * Math.sin(nz * 0.09 + 0.4) * 2.0;
            pos.setY(i, h);
        }
        groundGeo.computeVertexNormals();

        function makeGrassTexture(w = 256, h = 256) {
            const size = w * h * 3;
            const data = new Uint8Array(size);
            for (let y = 0; y < h; y++) {
                for (let x = 0; x < w; x++) {
                    const i = (y * w + x) * 3;
                    const u = x / w, v = y / h;
                    const noise =
                        Math.sin(u * 20.0) * 0.5 + Math.cos(v * 18.0) * 0.5 +
                        Math.sin((u + v) * 8.0) * 0.4;
                    const base = 80 + noise * 40;
                    const g = THREE.MathUtils.clamp(base + (v - 0.5) * 30, 50, 190);
                    const r = g * 0.6;
                    const b = g * 0.5;
                    data[i] = r; data[i + 1] = g; data[i + 2] = b;
                }
            }
            const tex = new THREE.DataTexture(data, w, h, THREE.RGBFormat);
            tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
            tex.needsUpdate = true;
            return tex;
        }
        const grassTex = makeGrassTexture(256, 256);
        grassTex.repeat.set(20, 20);
        const groundMat = new THREE.MeshStandardMaterial({
            map: grassTex,
            roughness: 1.0,
            metalness: 0.0,
            color: new THREE.Color(0x5c8b63).multiplyScalar(0.9)
        });
        const ground = new THREE.Mesh(groundGeo, groundMat);
        ground.receiveShadow = true;
        scene.add(ground);

        // Trees
        const treeGroup = new THREE.Group();
        scene.add(treeGroup);

        const trunkGeo = new THREE.CylinderGeometry(1, 1.8, 10, 8, 1, false);
        trunkGeo.translate(0, 5, 0);

        function makeFoliageGeometry() {
            const g = new THREE.BufferGeometry();
            const geometries = [];

            const cone1 = new THREE.ConeGeometry(6, 10, 8);
            cone1.translate(0, 14, 0); geometries.push(cone1);
            const cone2 = new THREE.ConeGeometry(5, 9, 8);
            cone2.translate(0, 20, 0); geometries.push(cone2);
            const cone3 = new THREE.ConeGeometry(4, 8, 8);
            cone3.translate(0, 25, 0); geometries.push(cone3);
            const sph = new THREE.SphereGeometry(3.5, 8, 6);
            sph.translate(0, 28.5, 0); geometries.push(sph);

            let totalVertices = 0, totalIndices = 0;
            for (const geo of geometries) {
                geo.computeVertexNormals();
                totalVertices += geo.attributes.position.count;
                totalIndices += geo.index ? geo.index.count : geo.attributes.position.count;
            }
            const posArr = new Float32Array(totalVertices * 3);
            const normArr = new Float32Array(totalVertices * 3);
            const uvArr = new Float32Array(totalVertices * 2);
            const indexArr = new Uint32Array(totalIndices);

            let vOffset = 0, iOffset = 0, baseVertex = 0;
            for (const geo of geometries) {
                const p = geo.attributes.position.array;
                const n = geo.attributes.normal.array;
                const u = geo.attributes.uv ? geo.attributes.uv.array : new Float32Array(geo.attributes.position.count * 2);
                posArr.set(p, vOffset * 3);
                normArr.set(n, vOffset * 3);
                uvArr.set(u, vOffset * 2);

                if (geo.index) {
                    const idx = geo.index.array;
                    for (let i = 0; i < idx.length; i++) indexArr[iOffset + i] = idx[i] + baseVertex;
                    iOffset += idx.length;
                } else {
                    for (let i = 0; i < geo.attributes.position.count; i++) indexArr[iOffset++] = baseVertex + i;
                }
                baseVertex += geo.attributes.position.count;
                vOffset += geo.attributes.position.count;
            }
            g.setAttribute('position', new THREE.BufferAttribute(posArr, 3));
            g.setAttribute('normal', new THREE.BufferAttribute(normArr, 3));
            g.setAttribute('uv', new THREE.BufferAttribute(uvArr, 2));
            g.setIndex(new THREE.BufferAttribute(indexArr, 1));
            g.computeBoundingSphere(); g.computeBoundingBox();
            return g;
        }

        const foliageGeo = makeFoliageGeometry();

        const trunkMat = new THREE.MeshStandardMaterial({
            color: 0x6b4f32, roughness: 0.9, metalness: 0.0
        });
        const foliageMat = new THREE.MeshStandardMaterial({
            color: 0x2f6b3d, roughness: 0.8, metalness: 0.0
        });

        let trunkInstanced, foliageInstanced;
        function makeInstancedMeshes(count) {
            if (trunkInstanced) treeGroup.remove(trunkInstanced);
            if (foliageInstanced) treeGroup.remove(foliageInstanced);
            trunkInstanced = new THREE.InstancedMesh(trunkGeo, trunkMat, count);
            trunkInstanced.castShadow = true; trunkInstanced.receiveShadow = true;
            foliageInstanced = new THREE.InstancedMesh(foliageGeo, foliageMat, count);
            foliageInstanced.castShadow = true; foliageInstanced.receiveShadow = true;
            treeGroup.add(trunkInstanced, foliageInstanced);
        }

        const wind = { strength: 0.35 };
        const rng = (seed => () => { seed = (seed * 1664525 + 1013904223) % 4294967296; return seed / 4294967296; })(123456789);

        const groundHeightAt = (x, z) => {
            const nx = x * 0.01, nz = z * 0.01;
            return Math.sin(nx) * Math.cos(nz) * 1.2 +
                   Math.sin(nx * 0.21 + 2.7) * Math.sin(nz * 0.19 + 1.5) * 0.7 +
                   Math.cos(nx * 0.07 - 1.1) * Math.sin(nz * 0.09 + 0.4) * 2.0;
        };

        let treeData = [];
        function regenerateForest(count, radius = areaSize.value) {
            makeInstancedMeshes(count);
            treeData.length = 0;

            const minSpacing = 4.0;
            const ext = radius;
            const attempts = count * 8;
            const points = [];
            for (let i = 0; i < attempts && points.length < count; i++) {
                const x = (rng() * 2 - 1) * ext;
                const z = (rng() * 2 - 1) * ext;
                const h = groundHeightAt(x, z);
                const hx = groundHeightAt(x + 1.0, z);
                const hz = groundHeightAt(x, z + 1.0);
                const slope = Math.hypot(hx - h, hz - h);
                if (slope > 1.2) continue;

                let ok = true;
                for (let p = 0; p < points.length; p++) {
                    const dx = x - points[p].x;
                    const dz = z - points[p].z;
                    if (dx * dx + dz * dz < minSpacing * minSpacing) { ok = false; break; }
                }
                if (!ok) continue;

                const t = {
                    x, z, h,
                    scale: 0.8 + rng() * 1.6,
                    type: rng() < 0.7 ? 'pine' : 'round',
                    swayPhase: rng() * Math.PI * 2,
                    swayAmp: 0.02 + rng() * 0.04
                };
                points.push({ x, z });
                treeData.push(t);
            }

            const m = new THREE.Matrix4();
            const q = new THREE.Quaternion();
            const up = new THREE.Vector3(0, 1, 0);
            for (let i = 0; i < treeData.length; i++) {
                const t = treeData[i];
                q.setFromAxisAngle(up, rng() * Math.PI * 2);
                m.compose(new THREE.Vector3(t.x, t.h, t.z), q, new THREE.Vector3(1, t.scale, 1));
                trunkInstanced.setMatrixAt(i, m);

                const foliageScale = 0.9 * t.scale;
                m.compose(new THREE.Vector3(t.x, t.h, t.z), q, new THREE.Vector3(foliageScale, foliageScale, foliageScale));
                foliageInstanced.setMatrixAt(i, m);

                const baseLeaf = new THREE.Color(0x2f6b3d);
                const shade = 0.8 + rng() * 0.4;
                const tint = baseLeaf.clone().multiplyScalar(shade);
                foliageInstanced.setColorAt(i, tint);

                const trunkColor = new THREE.Color(0x5c3f28).offsetHSL(0, 0, (rng() - 0.5) * 0.05);
                trunkInstanced.setColorAt(i, trunkColor);
            }
            trunkInstanced.instanceColor = new THREE.InstancedBufferAttribute(trunkInstanced.instanceColor.array, 3);
            foliageInstanced.instanceColor = new THREE.InstancedBufferAttribute(foliageInstanced.instanceColor.array, 3);
            trunkInstanced.instanceMatrix.needsUpdate = true;
            foliageInstanced.instanceMatrix.needsUpdate = true;
        }

        const windUniforms = { uTime: { value: 0 }, uStrength: { value: wind.strength } };
        foliageMat.onBeforeCompile = (shader) => {
            shader.uniforms.uTime = windUniforms.uTime;
            shader.uniforms.uStrength = windUniforms.uStrength;
            shader.vertexShader = `
                uniform float uTime;
                uniform float uStrength;
            ` + shader.vertexShader.replace(
                '#include <begin_vertex>',
                `
                #include <begin_vertex>
                float sway = sin(uTime * 1.7 + position.y * 0.35) * 0.5 + sin(uTime * 0.9 + position.y * 0.7) * 0.5;
                transformed.x += sway * uStrength * (0.4 + position.y * 0.06);
                transformed.z += cos(uTime * 1.1 + position.y * 0.42) * uStrength * (0.3 + position.y * 0.05);
                `
            );
        };
        foliageMat.needsUpdate = true;

        // Decorations
        const decoGroup = new THREE.Group(); scene.add(decoGroup);
        function makeRockGeometry() {
            const geo = new THREE.IcosahedronGeometry(1.0, 1);
            const arr = geo.attributes.position.array;
            for (let i = 0; i < arr.length; i += 3) {
                const r = 0.7 + rng() * 0.6;
                arr[i] *= r; arr[i + 1] *= (0.6 + rng() * 0.4 + 0.2); arr[i + 2] *= r;
            }
            geo.computeVertexNormals();
            return geo;
        }
        const rockGeo = makeRockGeometry();
        const rockMat = new THREE.MeshStandardMaterial({ color: 0x808a8f, roughness: 0.95, metalness: 0.0 });
        const rocksInst = new THREE.InstancedMesh(rockGeo, rockMat, 400);
        rocksInst.castShadow = true; rocksInst.receiveShadow = true; decoGroup.add(rocksInst);

        const grassBladeGeo = new THREE.PlaneGeometry(0.08, 1.2, 1, 3);
        grassBladeGeo.translate(0, 0.6, 0);
        const grassMat = new THREE.MeshStandardMaterial({ color: 0x5aa35f, side: THREE.DoubleSide, roughness: 1.0, metalness: 0.0 });
        const grassInst = new THREE.InstancedMesh(grassBladeGeo, grassMat, 2000);
        grassInst.castShadow = false; grassInst.receiveShadow = true; decoGroup.add(grassInst);

        function regenerateDecor(radius = areaSize.value) {
            const m = new THREE.Matrix4();
            const q = new THREE.Quaternion();

            const rockCount = rocksInst.count;
            const rockExt = radius * 0.95;
            for (let i = 0; i < rockCount; i++) {
                const x = (rng() * 2 - 1) * rockExt;
                const z = (rng() * 2 - 1) * rockExt;
                const h = groundHeightAt(x, z);
                q.setFromAxisAngle(new THREE.Vector3(0,1,0), rng() * Math.PI * 2);
                const s = 0.6 + rng() * 2.0;
                m.compose(new THREE.Vector3(x, h, z), q, new THREE.Vector3(s, s * (0.6 + rng() * 0.4), s));
                rocksInst.setMatrixAt(i, m);
                const shade = 0.8 + rng() * 0.3;
                const c = new THREE.Color().setRGB(0.6 * shade, 0.66 * shade, 0.72 * shade);
                rocksInst.setColorAt(i, c);
            }
            rocksInst.instanceMatrix.needsUpdate = true;
            if (!rocksInst.instanceColor) rocksInst.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(rockCount * 3), 3);
            rocksInst.instanceColor.needsUpdate = true;

            const grassCount = grassInst.count;
            const grassExt = radius;
            for (let i = 0; i < grassCount; i++) {
                const x = (rng() * 2 - 1) * grassExt;
                const z = (rng() * 2 - 1) * grassExt;
                const h = groundHeightAt(x, z);
                q.setFromAxisAngle(new THREE.Vector3(0,1,0), rng() * Math.PI * 2);
                const s = 0.7 + rng() * 0.6;
                m.compose(new THREE.Vector3(x, h, z), q, new THREE.Vector3(s, s, s));
                grassInst.setMatrixAt(i, m);
                const g = 0.7 + rng() * 0.3;
                const col = new THREE.Color(0x5aa35f).multiplyScalar(g);
                grassInst.setColorAt(i, col);
            }
            grassInst.instanceMatrix.needsUpdate = true;
            if (!grassInst.instanceColor) grassInst.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(grassCount * 3), 3);
            grassInst.instanceColor.needsUpdate = true;
        }

        // Atmosphere particles
        const particleGeo = new THREE.BufferGeometry();
        const PCOUNT = 800;
        const positions = new Float32Array(PCOUNT * 3);
               const speeds = new Float32Array(PCOUNT);
        const pColors = new Float32Array(PCOUNT * 3);
        for (let i = 0; i < PCOUNT; i++) {
            positions[i * 3] = (rng() * 2 - 1) * 250;
            positions[i * 3 + 1] = 1 + rng() * 12;
            positions[i * 3 + 2] = (rng() * 2 - 1) * 250;
            speeds[i] = 0.2 + rng() * 0.6;
            const c = new THREE.Color().setHSL(0.14 + rng() * 0.05, 0.4, 0.6 + rng() * 0.2);
            pColors[i * 3] = c.r; pColors[i * 3 + 1] = c.g; pColors[i * 3 + 2] = c.b;
        }
        particleGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
        particleGeo.setAttribute('aSpeed', new THREE.BufferAttribute(speeds, 1));
        particleGeo.setAttribute('color', new THREE.BufferAttribute(pColors, 3));
        const particleMat = new THREE.PointsMaterial({ size: 0.6, sizeAttenuation: true, transparent: true, opacity: 0.7, depthWrite: false, vertexColors: true });
        const particles = new THREE.Points(particleGeo, particleMat);
        scene.add(particles);

        // Water
        const waterGeo = new THREE.PlaneGeometry(200, 8, 1, 1);
        waterGeo.rotateX(-Math.PI / 2);
        const waterMat = new THREE.MeshPhysicalMaterial({
            color: 0x2a5b6b, roughness: 0.25, metalness: 0.0,
            transmission: 0.2, thickness: 0.2, transparent: true, opacity: 0.85,
            clearcoat: 0.4, clearcoatRoughness: 0.3
        });
        const water = new THREE.Mesh(waterGeo, waterMat);
        water.position.set(0, groundHeightAt(0, 0) - 0.2, 0);
        water.receiveShadow = true;
        scene.add(water);

        // Camera and controls
        const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1200);
        camera.position.set(60, 40, 80);
        const controls = new OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true; controls.dampingFactor = 0.05;
        controls.maxPolarAngle = Math.PI * 0.495;
        controls.target.set(0, 8, 0); controls.update();

        // Initial generation
        regenerateForest(550, areaSize.value);
        regenerateDecor(areaSize.value);

        // Sync UI to scene after initial generation
        setSunFromUI();
        setHemiFromUI();
        setWindFromUI();
        setAreaFromUI();

        // STARFIELD
        function addStars() {
            const starGeo = new THREE.BufferGeometry();
            const STAR_COUNT = 4000;
            const starPos = new Float32Array(STAR_COUNT * 3);
            const starCol = new Float32Array(STAR_COUNT * 3);

            // Distribute stars on a sphere shell to avoid fog-thick inner region
            const radiusMin = 500;
            const radiusMax = 900;
            for (let i = 0; i < STAR_COUNT; i++) {
                const u = rng();
                const v = rng();
                const theta = 2 * Math.PI * u;
                const phi = Math.acos(2 * v - 1);
                const r = radiusMin + rng() * (radiusMax - radiusMin);
                const x = r * Math.sin(phi) * Math.cos(theta);
                const y = r * Math.cos(phi);
                const z = r * Math.sin(phi) * Math.sin(theta);
                starPos[i * 3] = x;
                starPos[i * 3 + 1] = y;
                starPos[i * 3 + 2] = z;

                const twinkle = 0.85 + rng() * 0.3;
                const c = new THREE.Color().setHSL(0.57 + rng() * 0.1, 0.1 + rng() * 0.2, 0.9 * twinkle);
                starCol[i * 3] = c.r; starCol[i * 3 + 1] = c.g; starCol[i * 3 + 2] = c.b;
            }
            starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3));
            starGeo.setAttribute('color', new THREE.BufferAttribute(starCol, 3));

            const starMat = new THREE.PointsMaterial({
                size: 1.4,
                sizeAttenuation: true,
                depthWrite: false,
                transparent: true,
                opacity: 0.95,
                vertexColors: true
            });

            const stars = new THREE.Points(starGeo, starMat);
            stars.renderOrder = -1;
            scene.add(stars);

            // Soft nebula background using a big inverted sphere with emissive color
            const skyGeo = new THREE.SphereGeometry(1200, 32, 16);
            skyGeo.scale(-1, 1, 1); // inward facing
            const skyMat = new THREE.MeshBasicMaterial({
                color: 0x0b1216
            });
            const sky = new THREE.Mesh(skyGeo, skyMat);
            scene.add(sky);

            // Subtle rotation for parallax feel
            return { stars, sky };
        }
        const starfield = addStars();



        densityEl.addEventListener('input', () => {
            const count = parseInt(densityEl.value, 10);
            densityVal.textContent = count;
            regenerateForest(count, areaSize.value);
        });
        windEl.addEventListener('input', () => {
            const v = parseInt(windEl.value, 10) / 100;
            wind.strength = v;
            windUniforms.uStrength.value = v;
            windVal.textContent = v.toFixed(2);
        });
        sizeEl.addEventListener('input', () => {
            const v = parseInt(sizeEl.value, 10);
            areaSize.value = v;
            sizeVal.textContent = v;
            regenerateForest(parseInt(densityEl.value, 10), v);
            regenerateDecor(v);
        });

        function updateSunFromUI() {
            const intensity = parseInt(sunIntEl.value, 10) / 100;
            const elevDeg = parseInt(sunElevEl.value, 10);
            const azimDeg = parseInt(sunAzimEl.value, 10);
            const elev = THREE.MathUtils.degToRad(elevDeg);
            const azim = THREE.MathUtils.degToRad(azimDeg);

            dirLight.intensity = intensity;
            const r = 180;
            const y = Math.sin(elev) * r;
            const horiz = Math.cos(elev) * r;
            const x = Math.cos(azim) * horiz;
            const z = Math.sin(azim) * horiz;
            dirLight.position.set(x, y, z);

            sunIntVal.textContent = intensity.toFixed(2);
            sunElevVal.textContent = elevDeg + '°';
            sunAzimVal.textContent = azimDeg + '°';
        }
        function updateHemiFromUI() {
            const v = parseInt(hemiEl.value, 10) / 100;
            hemiLight.intensity = v;
            hemiVal.textContent = v.toFixed(2);
        }
        sunIntEl.addEventListener('input', updateSunFromUI);
        sunElevEl.addEventListener('input', updateSunFromUI);
        sunAzimEl.addEventListener('input', updateSunFromUI);
        hemiEl.addEventListener('input', updateHemiFromUI);
        updateSunFromUI();
        updateHemiFromUI();

        // Keyboard movement (arrow keys) - moves camera in view plane
        const keys = { ArrowUp: false, ArrowDown: false, ArrowLeft: false, ArrowRight: false, ShiftLeft: false, ShiftRight: false };
        function setKey(code, down) {
            if (code in keys) {
                keys[code] = down;
                return true;
            }
            return false;
        }
        // Use key property for better cross-browser Arrow naming, fallback to code
        window.addEventListener('keydown', (e) => {
            const hit = setKey(e.key || e.code, true) || setKey(e.code, true);
            if (hit) { e.preventDefault(); }
        }, { passive: false });
        window.addEventListener('keyup', (e) => {
            const hit = setKey(e.key || e.code, false) || setKey(e.code, false);
            if (hit) { e.preventDefault(); }
        }, { passive: false });
        // Also allow WASD
        window.addEventListener('keydown', (e) => {
            if (e.key === 'w' || e.key === 'W') { keys.ArrowUp = true; e.preventDefault(); }
            if (e.key === 's' || e.key === 'S') { keys.ArrowDown = true; e.preventDefault(); }
            if (e.key === 'a' || e.key === 'A') { keys.ArrowLeft = true; e.preventDefault(); }
            if (e.key === 'd' || e.key === 'D') { keys.ArrowRight = true; e.preventDefault(); }
        }, { passive: false });
        window.addEventListener('keyup', (e) => {
            if (e.key === 'w' || e.key === 'W') { keys.ArrowUp = false; e.preventDefault(); }
            if (e.key === 's' || e.key === 'S') { keys.ArrowDown = false; e.preventDefault(); }
            if (e.key === 'a' || e.key === 'A') { keys.ArrowLeft = false; e.preventDefault(); }
            if (e.key === 'd' || e.key === 'D') { keys.ArrowRight = false; e.preventDefault(); }
        }, { passive: false });

        function updateKeyboardMovement(dt) {
            const speedBase = 25; // units per second
            const boost = (keys.ShiftLeft || keys.ShiftRight) ? 3.0 : 1.0;
            const speed = speedBase * boost;

            let inputX = 0, inputZ = 0;
            if (keys.ArrowUp) inputZ -= 1;
            if (keys.ArrowDown) inputZ += 1;
            if (keys.ArrowLeft) inputX -= 1;
            if (keys.ArrowRight) inputX += 1;

            if (inputX !== 0 || inputZ !== 0) {
                const forward = new THREE.Vector3();
                camera.getWorldDirection(forward);
                forward.y = 0; forward.normalize();
                // Right vector should be forward cross up
                const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0,1,0)).normalize();

                const move = new THREE.Vector3()
                    .addScaledVector(forward, inputZ)
                    .addScaledVector(right, inputX)
                    .normalize()
                    .multiplyScalar(speed * dt);

                camera.position.add(move);
                controls.target.add(move);
            }
        }

        // Animation loop
        const clock = new THREE.Clock();
        function animate() {
            requestAnimationFrame(animate);
            const t = clock.getElapsedTime();
            const dt = clock.getDelta();

            windUniforms.uTime.value = t;

            // Particle drift
            const posAttr = particles.geometry.getAttribute('position');
            const spdAttr = particles.geometry.getAttribute('aSpeed');
            for (let i = 0; i < PCOUNT; i++) {
                const y = posAttr.getY(i);
                const x = posAttr.getX(i);
                const z = posAttr.getZ(i);
                const s = spdAttr.getX(i);
                const nx = x + Math.sin(t * 0.6 + i) * 0.02;
                const nz = z + Math.cos(t * 0.5 + i * 1.3) * 0.02;
                let ny = y + (Math.sin(t * s + i) * 0.003 + 0.002);
                if (ny > 14) ny = 1 + rng() * 2;
                posAttr.setXYZ(i, nx, ny, nz);
            }
            posAttr.needsUpdate = true;

            // Subtle star rotation for life
            if (starfield && starfield.stars) {
                starfield.stars.rotation.y = t * 0.002;
                starfield.stars.rotation.x = Math.sin(t * 0.05) * 0.02;
            }

            // Keyboard move
            updateKeyboardMovement(dt);

            controls.update();
            renderer.render(scene, camera);
        }
        animate();

        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        });

        // Ensure canvas focus on click so arrow keys work immediately
        renderer.domElement.addEventListener('pointerdown', () => renderer.domElement.focus());
    </script>
</body>
</html>