-
Notifications
You must be signed in to change notification settings - Fork 69
/
rainbow-quest.html
1439 lines (1106 loc) · 56.7 KB
/
rainbow-quest.html
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>
<head>
<title>Rainbow Quest (work in progress)</title>
<meta name="description" content="Rainbow Quest (work in progress)">
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=">
<script src="js/aframe-master-v1.3.0.js"></script>
<script src="js/rainbow-quest.js"></script>
<script src="js/gltf-modify.js"></script>
<script src="js/howler.js"></script>
</head>
<body>
<script>
let rainbowMaterial = new THREE.ShaderMaterial({
uniforms:
{
time: { value: 0 },
},
fragmentShader:
`
uniform float time;
// convert HSV color data to RGB color data
vec3 hsv2rgb(vec3 c)
{
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
void main()
{
float hue = mod(time / 20.0, 1.0);
vec3 color = hsv2rgb( vec3(hue, 0.5, 1.0) );
gl_FragColor = vec4( color, 1.0 );
}
`
})
function makeUberMaterial(diffuseMap, normalMap, thickness=0.05)
{
let material = new THREE.ShaderMaterial({
uniforms: THREE.UniformsUtils.merge([
THREE.UniformsLib[ "common" ], // defines uniforms and sets defaults: vec3 diffuse, float opacity, mat3 uvTransform, sampler2D map
THREE.UniformsLib[ "lights" ], // values automatically sent by three.js
THREE.UniformsLib[ "normalmap" ], // defines uniforms and sets defaults: sampler2D normalMap, vec2 normalScale
THREE.UniformsLib[ "fog" ], // values automatically sent by three.js
{
time: { value: 0 },
shininess: { value: 10 },
specular: { value: new THREE.Color("#111111") },
emissive: { value: new THREE.Color("#000000") },
thickness: { value: thickness },
roomEffect: { value: [0, 0,0,0,0,0,0, -1,-1,-1,-1,-1,-1] },
}
]),
lights: true,
fog: true,
vertexShader:
`
${THREE.ShaderChunk["common"]}
#define USE_UV
${THREE.ShaderChunk["uv_pars_vertex"]}
attribute vec3 color;
#define USE_COLOR
${THREE.ShaderChunk["color_pars_vertex"]}
varying vec3 vViewPosition;
${THREE.ShaderChunk["normal_pars_vertex"]}
${THREE.ShaderChunk["fog_pars_vertex"]}
// wallData: [N,E,S,W]. 0=absent, 1=present.
attribute vec4 wallData;
varying vec4 vWallData;
// cornerData: [NE, SE, SW, NW]. 0=absent, 1=present.
attribute vec4 cornerData;
varying vec4 vCornerData;
attribute float textureRepeat;
varying float vTextureRepeat;
// determine which of the room visual effects (-1, 0, 1) to apply to this area
attribute int roomId;
uniform float roomEffect[13];
varying float vEffectId;
void main()
{
${THREE.ShaderChunk["uv_vertex"]}
${THREE.ShaderChunk["color_vertex"]}
${THREE.ShaderChunk["begin_vertex"]}
${THREE.ShaderChunk["project_vertex"]}
${THREE.ShaderChunk["beginnormal_vertex"]}
${THREE.ShaderChunk["defaultnormal_vertex"]}
${THREE.ShaderChunk["normal_vertex"]}
vViewPosition = - mvPosition.xyz;
${THREE.ShaderChunk["fog_vertex"]}
vTextureRepeat = textureRepeat;
vWallData = wallData;
vCornerData = cornerData;
vEffectId = roomEffect[roomId];
}
`,
fragmentShader: `
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
varying vec4 vWallData;
varying vec4 vCornerData;
uniform float thickness;
varying float vTextureRepeat;
varying float vEffectId;
uniform float time;
${THREE.ShaderChunk["common"]}
${THREE.ShaderChunk["packing"]}
#define USE_COLOR
${THREE.ShaderChunk["color_pars_fragment"]}
#define USE_UV
${THREE.ShaderChunk["uv_pars_fragment"]}
#define USE_MAP
${THREE.ShaderChunk["map_pars_fragment"]}
${THREE.ShaderChunk["emissivemap_pars_fragment"]}
${THREE.ShaderChunk["bsdfs"]}
${THREE.ShaderChunk["lights_pars_begin"]}
${THREE.ShaderChunk["normal_pars_fragment"]}
${THREE.ShaderChunk["lights_phong_pars_fragment"]}
#define USE_NORMALMAP
#define TANGENTSPACE_NORMALMAP
${THREE.ShaderChunk["normalmap_pars_fragment"]}
${THREE.ShaderChunk["specularmap_pars_fragment"]}
${THREE.ShaderChunk["fog_pars_fragment"]}
// convert HSV color data to RGB color data
vec3 hsv2rgb(vec3 c)
{
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
// Perlin noise shader.
// Copyright (c) 2011 Stefan Gustavson. All rights reserved.
// Distributed under the MIT license. See LICENSE file.
// https://github.com/stegu/webgl-noise
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec4 permute(vec4 x) { return mod289(((x*34.0)+10.0)*x); }
vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
vec3 fade(vec3 t) { return t*t*t*(t*(t*6.0-15.0)+10.0); }
// Classic Perlin noise
float cnoise(vec3 P)
{
vec3 Pi0 = floor(P); // Integer part for indexing
vec3 Pi1 = Pi0 + vec3(1.0); // Integer part + 1
Pi0 = mod289(Pi0);
Pi1 = mod289(Pi1);
vec3 Pf0 = fract(P); // Fractional part for interpolation
vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0
vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x);
vec4 iy = vec4(Pi0.yy, Pi1.yy);
vec4 iz0 = Pi0.zzzz;
vec4 iz1 = Pi1.zzzz;
vec4 ixy = permute(permute(ix) + iy);
vec4 ixy0 = permute(ixy + iz0);
vec4 ixy1 = permute(ixy + iz1);
vec4 gx0 = ixy0 * (1.0 / 7.0);
vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;
gx0 = fract(gx0);
vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0);
vec4 sz0 = step(gz0, vec4(0.0));
gx0 -= sz0 * (step(0.0, gx0) - 0.5);
gy0 -= sz0 * (step(0.0, gy0) - 0.5);
vec4 gx1 = ixy1 * (1.0 / 7.0);
vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;
gx1 = fract(gx1);
vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1);
vec4 sz1 = step(gz1, vec4(0.0));
gx1 -= sz1 * (step(0.0, gx1) - 0.5);
gy1 -= sz1 * (step(0.0, gy1) - 0.5);
vec3 g000 = vec3(gx0.x,gy0.x,gz0.x);
vec3 g100 = vec3(gx0.y,gy0.y,gz0.y);
vec3 g010 = vec3(gx0.z,gy0.z,gz0.z);
vec3 g110 = vec3(gx0.w,gy0.w,gz0.w);
vec3 g001 = vec3(gx1.x,gy1.x,gz1.x);
vec3 g101 = vec3(gx1.y,gy1.y,gz1.y);
vec3 g011 = vec3(gx1.z,gy1.z,gz1.z);
vec3 g111 = vec3(gx1.w,gy1.w,gz1.w);
vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110)));
g000 *= norm0.x;
g010 *= norm0.y;
g100 *= norm0.z;
g110 *= norm0.w;
vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111)));
g001 *= norm1.x;
g011 *= norm1.y;
g101 *= norm1.z;
g111 *= norm1.w;
float n000 = dot(g000, Pf0);
float n100 = dot(g100, vec3(Pf1.x, Pf0.yz));
float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z));
float n110 = dot(g110, vec3(Pf1.xy, Pf0.z));
float n001 = dot(g001, vec3(Pf0.xy, Pf1.z));
float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z));
float n011 = dot(g011, vec3(Pf0.x, Pf1.yz));
float n111 = dot(g111, Pf1);
vec3 fade_xyz = fade(Pf0);
vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z);
vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y);
float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x);
return 2.2 * n_xyz;
}
void main()
{
vec4 diffuseColor = vec4( diffuse, opacity );
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
vec3 totalEmissiveRadiance = emissive;
// for standard fragment shader, would normally use:
// ShaderChunk["map_fragment"]
// ShaderChunk["color_fragment"]
// custom color effects
// option 0: use vColor & diffuse texture
// option +1: hue shift & diffuse texture
vec3 hueShiftColor = hsv2rgb( vec3(mod(time / 20.0, 1.0), 0.5, 1.0) );
// option -1: perlin noise (no diffuse texture BUT still apply normal texture)
float n = (cnoise( 20.0 * vec3(vUv.x * vTextureRepeat, vUv.y * vTextureRepeat, time/100.0)) + 1.0) / 2.1;
vec3 perlinNoiseColor = 0.90 * vec3( n,n,n );
// vec3 perlinNoiseColor = vec3(0.20);
// simple variation when WebGL context keeps getting lost...
diffuseColor.rgb *= texture2D(map, vUv * vTextureRepeat).rgb;
// select option based on vEffectId:
diffuseColor.rgb *= (vEffectId < -0.5) ? perlinNoiseColor :
( (vEffectId < 0.5) ? vColor : hueShiftColor );
${THREE.ShaderChunk["specularmap_fragment"]}
${THREE.ShaderChunk["normal_fragment_begin"]}
// from ShaderChunk["normal_fragment_maps"] & adding repeatUV
vec3 mapN = texture2D( normalMap, vUv * vTextureRepeat ).xyz * 2.0 - 1.0;
mapN.xy *= normalScale;
normal = perturbNormal2Arb( -vViewPosition, normal, mapN, faceDirection );
${THREE.ShaderChunk["emissivemap_fragment"]}
// accumulation
${THREE.ShaderChunk["lights_phong_fragment"]}
${THREE.ShaderChunk["lights_fragment_begin"]}
${THREE.ShaderChunk["lights_fragment_maps"]}
${THREE.ShaderChunk["lights_fragment_end"]}
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
// assign gl_FragColor
${THREE.ShaderChunk["output_fragment"]}
// using ternary rather than if statements, hopefully for increased WebGL stability
// north wall
gl_FragColor.rgb *= (vWallData.x > 0.5 && vUv.y > 1.0 - thickness) ?
mix(0.25, 1.0, (1.0 - vUv.y) / thickness) : 1.0;
// east wall
gl_FragColor.rgb *= (vWallData.y > 0.5 && vUv.x > 1.0 - thickness) ?
mix(0.25, 1.0, (1.0 - vUv.x) / thickness) : 1.0;
// south wall
gl_FragColor.rgb *= (vWallData.z > 0.5 && vUv.y < thickness) ?
mix(0.25, 1.0, vUv.y / thickness) : 1.0;
// west wall
gl_FragColor.rgb *= (vWallData.w > 0.5 && vUv.x < thickness) ?
mix(0.25, 1.0, vUv.x / thickness) : 1.0;
// NE corner
gl_FragColor.rgb *= (vCornerData.x > 0.5 && vUv.x > 1.0 - thickness && vUv.y > 1.0 - thickness) ?
mix(0.25, 1.0, min( distance(vUv, vec2(1,1))/thickness, 1.0) ) : 1.0;
// SE corner
gl_FragColor.rgb *= (vCornerData.y > 0.5 && vUv.x > 1.0 - thickness && vUv.y < thickness) ?
mix(0.25, 1.0, min( distance(vUv, vec2(1,0))/thickness, 1.0) ) : 1.0;
// SW corner
gl_FragColor.rgb *= (vCornerData.z > 0.5 && vUv.x < thickness && vUv.y < thickness) ?
mix(0.25, 1.0, min( distance(vUv, vec2(0,0))/thickness, 1.0) ) : 1.0;
// NW corner
gl_FragColor.rgb *= (vCornerData.w > 0.5 && vUv.x < thickness && vUv.y > 1.0 - thickness) ?
mix(0.25, 1.0, min( distance(vUv, vec2(0,1))/thickness, 1.0) ) : 1.0;
${THREE.ShaderChunk["fog_fragment"]}
}
`
}); // end of ShaderMaterial
// create textures from images
let mapTexture = new THREE.Texture();
mapTexture.image = document.querySelector(diffuseMap);
mapTexture.wrapS = THREE.RepeatWrapping;
mapTexture.wrapT = THREE.RepeatWrapping;
mapTexture.needsUpdate = true;
material.uniforms.map.value = mapTexture;
let normalTexture = new THREE.Texture();
normalTexture.image = document.querySelector(normalMap);
normalTexture.wrapS = THREE.RepeatWrapping;
normalTexture.wrapT = THREE.RepeatWrapping;
normalTexture.needsUpdate = true;
material.uniforms.normalMap.value = normalTexture;
return material;
};
// game code ------------------------------------------------------------------------------------------------------------
AFRAME.registerComponent("rainbow-quest", {
init: function ()
{
let self = this;
// TODO: resume game if WebGL context is lost?
// generate dungeon data ------------------------------------------------------------
this.rainbowQuest = new RainbowQuest();
this.rainbowQuest.generateDungeon();
while (this.rainbowQuest.getCellWithType(Cell.PATH) == null)
{
console.log("Unsolvable dungeon created, restarting...");
this.rainbowQuest.reset();
this.rainbowQuest.generateDungeon();
}
// build 3D model of dungeon ---------------------------------------------------------
// merge geometries to reduce number of draw calls and save FPS
// (x,y,z): min corner of the object
// floor tiles; used for Cell.PATH and Cell.ROOM
function createFloorPlaneGeom(x,y,z, w,h)
{
let planeGeom = new THREE.PlaneGeometry(w, h);
planeGeom.rotateX(-Math.PI/2);
planeGeom.translate(x + w/2, y, z + h/2);
return planeGeom;
}
function createWallPlaneGeom(centerX, centerY, centerZ, width, height, roomSide)
{
let planeGeom = new THREE.PlaneGeometry(width, height);
if (roomSide == "N")
{
// planeGeom.rotateY(0);
planeGeom.translate(centerX + width/2, centerY + height/2, centerZ);
}
else if (roomSide == "E")
{
planeGeom.rotateY(-Math.PI/2);
planeGeom.translate(centerX + width, centerY + height/2, centerZ + width/2);
}
else if (roomSide == "S")
{
planeGeom.rotateY(Math.PI);
planeGeom.translate(centerX + width/2, centerY + height/2, centerZ + width);
}
else if (roomSide == "W")
{
planeGeom.rotateY(Math.PI/2);
planeGeom.translate(centerX, centerY + height/2, centerZ + width/2);
}
return planeGeom;
}
// color data buffers-------------------------------------------------------
let white = [1, 1, 1], gray = [0.5, 0.5, 0.5], darkGray = [0.15, 0.15, 0.15],
red = [1, 0.5, 0.5], orange = [1, 0.75, 0.5], yellow = [1, 1, 0.5],
green = [0.5, 1, 0.5], blue = [0.5, 0.75, 1], purple = [0.75, 0.5, 1];
let roomColorData = [
gray, red, orange, yellow, green, blue, purple,
gray, gray, gray, gray, gray, gray ];
let roomColorBufferArray = [];
for (let i = 0; i < roomColorData.length; i++)
roomColorBufferArray.push( new THREE.BufferAttribute(
new Float32Array( new Array(4).fill(roomColorData[i]).flat() ), 3 ) );
// shadow data buffers ---------------------------------------------------------
let shadowData = [
[0,0,0,0], [1,0,0,0], [0,1,0,0], [1,1,0,0],
[0,0,1,0], [1,0,1,0], [0,1,1,0], [1,1,1,0],
[0,0,0,1], [1,0,0,1], [0,1,0,1], [1,1,0,1],
[0,0,1,1], [1,0,1,1], [0,1,1,1], [1,1,1,1]
];
let shadowBufferArray = [];
let shadowBufferIndex = 0;
for (let i = 0; i < shadowData.length; i++)
shadowBufferArray.push( new THREE.BufferAttribute(
new Float32Array( new Array(4).fill(shadowData[i]).flat() ), 4 ) );
// roomId data buffers ---------------------------------------------------------
let roomIdBufferArray = []
for (let i = 0; i < roomColorData.length; i++)
roomIdBufferArray.push( new THREE.BufferAttribute(
new Int32Array( new Array(4).fill(i).flat() ), 1 ) );
// textureRepeat buffers -------------------------------------------------------
// path floor
let textureRepeat1Buffer = new THREE.BufferAttribute(
new Float32Array( new Array(4).fill(1).flat() ), 1 );
// walls
let textureRepeat2Buffer = new THREE.BufferAttribute(
new Float32Array( new Array(4).fill(2).flat() ), 1 );
// room floor
let textureRepeat5Buffer = new THREE.BufferAttribute(
new Float32Array( new Array(4).fill(5).flat() ), 1 );
// combine path and room data into a single "floor geometry" --------------
let floorGeomChunks = {};
let floorGeomArray = [];
// path geometry ----------------------------------------------------------
for (let i = 0; i < this.rainbowQuest.numCellHoriz; i++)
for (let j = 0; j < this.rainbowQuest.numCellVert; j++)
{
let cell = this.rainbowQuest.cellArray[i][j];
// create a "tile" at the bottom of this location
if (cell.type == Cell.PATH)
{
let geo = createFloorPlaneGeom(i, 0, j, 1, 1);
// calculate floor ambient occlusion data based on wall presence
let wallData = [0,0,0,0];
if (cell.getWall("N") != null && cell.getWall("N").visible)
wallData[0] = 1;
if (cell.getWall("E") != null && cell.getWall("E").visible)
wallData[1] = 1;
if (cell.getWall("S") != null && cell.getWall("S").visible)
wallData[2] = 1;
if (cell.getWall("W") != null && cell.getWall("W").visible)
wallData[3] = 1;
let cornerData = [0,0,0,0];
let cellNE = this.rainbowQuest.cellArray.get2D(i+1, j-1);
if (cellNE != null && wallData[0] == 0 && wallData[1] == 0 &&
((cellNE.getWall("W") != null && cellNE.getWall("W").visible) ||
(cellNE.getWall("S") != null && cellNE.getWall("S").visible)) )
cornerData[0] = 1;
let cellSE = this.rainbowQuest.cellArray.get2D(i+1, j+1);
if (cellSE != null && wallData[2] == 0 && wallData[1] == 0 &&
((cellSE.getWall("W") != null && cellSE.getWall("W").visible) ||
(cellSE.getWall("N") != null && cellSE.getWall("N").visible)) )
cornerData[1] = 1;
let cellSW = this.rainbowQuest.cellArray.get2D(i-1, j+1);
if (cellSW != null && wallData[2] == 0 && wallData[3] == 0 &&
((cellSW.getWall("E") != null && cellSW.getWall("E").visible) ||
(cellSW.getWall("N") != null && cellSW.getWall("N").visible)) )
cornerData[2] = 1;
let cellNW = this.rainbowQuest.cellArray.get2D(i-1, j-1);
if (cellNW != null && wallData[0] == 0 && wallData[3] == 0 &&
((cellNW.getWall("E") != null && cellNW.getWall("E").visible) ||
(cellNW.getWall("S") != null && cellNW.getWall("S").visible)) )
cornerData[3] = 1;
shadowBufferIndex = wallData[0] * 1 + wallData[1] * 2 + wallData[2] * 4 + wallData[3] * 8;
geo.setAttribute( 'wallData', shadowBufferArray[shadowBufferIndex] );
shadowBufferIndex = cornerData[0] * 1 + cornerData[1] * 2 + cornerData[2] * 4 + cornerData[3] * 8;
geo.setAttribute( 'cornerData', shadowBufferArray[shadowBufferIndex] );
// vertex colors & room Id
geo.setAttribute( 'color', roomColorBufferArray[0] );
geo.setAttribute( 'roomId', roomIdBufferArray[0] );
geo.setAttribute( 'textureRepeat', textureRepeat1Buffer );
// add to a chunk
let key = Math.floor(i/5) + ":" + Math.floor(j/5);
if ( floorGeomChunks[key] == null )
floorGeomChunks[key] = [];
floorGeomChunks[key].push( geo );
}
}
this.floorMaterial = makeUberMaterial("#pathDiffuse", "#pathNormal");
let roomElement = document.getElementById("roomEntity");
// set up mesh for each chunk
for (let key in floorGeomChunks)
{
let floorGeometry0 = THREE.BufferGeometryUtils.mergeBufferGeometries( floorGeomChunks[key] );
// trying to clear up memory
for (let n = 0; n < floorGeomChunks[key].length; n++)
floorGeomChunks[key][n].dispose();
floorGeomChunks[key] = [];
let floor = new THREE.Mesh(floorGeometry0, this.floorMaterial);
roomElement.object3D.add(floor);
}
// room geometry --------------------------------------------------------------
// each room is 5x5
for (let i = 0; i < 13; i++)
{
let room = this.rainbowQuest.roomArray[i];
let geo = createFloorPlaneGeom(room.x, 0, room.y, room.w, room.h);
geo.setAttribute( 'wallData', shadowBufferArray[15] );
geo.setAttribute( 'cornerData', shadowBufferArray[0] );
// vertex colors & room Id
geo.setAttribute( 'color', roomColorBufferArray[i] );
geo.setAttribute( 'roomId', roomIdBufferArray[i] );
geo.setAttribute( 'textureRepeat', textureRepeat5Buffer );
floorGeomArray.push( geo );
}
// floor (path + room) mesh --------------------------------------------------------
let floorGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries( floorGeomArray );
// trying to clear up memory
for (let n = 0; n < floorGeomArray.length; n++)
floorGeomArray[n].dispose();
floorGeomArray = [];
let floor = new THREE.Mesh(floorGeometry, this.floorMaterial);
// TODO: change to floorEntity
roomElement.object3D.add(floor);
// walls --------------------------------------------------------------
let wallGeomChunks = {};
let wallGeomArray = [];
let wallWidth = 1;
let wallHeight = 1;
// reusable buffer
let cornerDataBufferAttribute = new THREE.BufferAttribute(
new Float32Array( new Array(4).fill([0,0,0,0]).flat() ), 4 );
for (let i = 0; i < this.rainbowQuest.numCellHoriz; i++)
for (let j = 0; j < this.rainbowQuest.numCellVert; j++)
{
let cell = this.rainbowQuest.cellArray[i][j];
let key = Math.floor(i/5) + ":" + Math.floor(j/5);
if ( wallGeomChunks[key] == null )
wallGeomChunks[key] = [];
// create the "wall tiles" (up to 4) for this cell
if (cell.type == Cell.PATH || cell.type == Cell.ROOM)
{
if (cell.getWall("N") != null && cell.getWall("N").visible)
{
let geo = createWallPlaneGeom(i, 0, j, wallWidth, wallHeight, "N");
let wallData = [1,0,1,0];
// if in a corner, add extra shading
if (cell.getWall("E") != null && cell.getWall("E").visible)
wallData[1] = 1;
if (cell.getWall("W") != null && cell.getWall("W").visible)
wallData[3] = 1;
shadowBufferIndex = wallData[0] * 1 + wallData[1] * 2 + wallData[2] * 4 + wallData[3] * 8;
geo.setAttribute( 'wallData', shadowBufferArray[shadowBufferIndex] );
geo.setAttribute( 'cornerData', shadowBufferArray[0] );
// vertex colors & room Id
geo.setAttribute( 'color', roomColorBufferArray[cell.roomId] );
geo.setAttribute( 'roomId', roomIdBufferArray[cell.roomId] );
geo.setAttribute( 'textureRepeat', textureRepeat2Buffer );
// wallGeomArray.push( geo );
wallGeomChunks[key].push( geo );
}
if (cell.getWall("E") != null && cell.getWall("E").visible)
{
let geo = createWallPlaneGeom(i, 0, j, wallWidth, wallHeight, "E");
let wallData = [1,0,1,0];
// if in a corner, add extra shading
if (cell.getWall("N") != null && cell.getWall("N").visible)
wallData[3] = 1;
if (cell.getWall("S") != null && cell.getWall("S").visible)
wallData[1] = 1;
shadowBufferIndex = wallData[0] * 1 + wallData[1] * 2 + wallData[2] * 4 + wallData[3] * 8;
geo.setAttribute( 'wallData', shadowBufferArray[shadowBufferIndex] );
geo.setAttribute( 'cornerData', shadowBufferArray[0] );
// vertex colors & room Id
geo.setAttribute( 'color', roomColorBufferArray[cell.roomId] );
geo.setAttribute( 'roomId', roomIdBufferArray[cell.roomId] );
geo.setAttribute( 'textureRepeat', textureRepeat2Buffer );
// wallGeomArray.push( geo );
wallGeomChunks[key].push( geo );
}
if (cell.getWall("S") != null && cell.getWall("S").visible)
{
let geo = createWallPlaneGeom(i, 0, j, wallWidth, wallHeight, "S");
let wallData = [1,0,1,0];
// if in a corner, add extra shading
if (cell.getWall("E") != null && cell.getWall("E").visible)
wallData[3] = 1;
if (cell.getWall("W") != null && cell.getWall("W").visible)
wallData[1] = 1;
shadowBufferIndex = wallData[0] * 1 + wallData[1] * 2 + wallData[2] * 4 + wallData[3] * 8;
geo.setAttribute( 'wallData', shadowBufferArray[shadowBufferIndex] );
geo.setAttribute( 'cornerData', shadowBufferArray[0] );
// vertex colors & room Id
geo.setAttribute( 'color', roomColorBufferArray[cell.roomId] );
geo.setAttribute( 'roomId', roomIdBufferArray[cell.roomId] );
geo.setAttribute( 'textureRepeat', textureRepeat2Buffer );
// wallGeomArray.push( geo );
wallGeomChunks[key].push( geo );
}
if (cell.getWall("W") != null && cell.getWall("W").visible)
{
let geo = createWallPlaneGeom(i, 0, j, wallWidth, wallHeight, "W");
let wallData = [1,0,1,0];
// if in a corner, add extra shading
if (cell.getWall("N") != null && cell.getWall("N").visible)
wallData[1] = 1;
if (cell.getWall("S") != null && cell.getWall("S").visible)
wallData[3] = 1;
shadowBufferIndex = wallData[0] * 1 + wallData[1] * 2 + wallData[2] * 4 + wallData[3] * 8;
geo.setAttribute( 'wallData', shadowBufferArray[shadowBufferIndex] );
geo.setAttribute( 'cornerData', shadowBufferArray[0] );
// vertex colors & room Id
geo.setAttribute( 'color', roomColorBufferArray[cell.roomId] );
geo.setAttribute( 'roomId', roomIdBufferArray[cell.roomId] );
geo.setAttribute( 'textureRepeat', textureRepeat2Buffer );
// wallGeomArray.push( geo );
wallGeomChunks[key].push( geo );
}
}
}
this.wallMaterial = makeUberMaterial("#wallDiffuse", "#wallNormal");
// set up mesh for each chunk
for (let key in wallGeomChunks)
{
if (wallGeomChunks[key].length == 0)
continue;
let wallGeometry0 = THREE.BufferGeometryUtils.mergeBufferGeometries( wallGeomChunks[key] );
// trying to clear up memory
for (let n = 0; n < wallGeomChunks[key].length; n++)
wallGeomChunks[key][n].dispose();
wallGeomChunks[key] = [];
let mesh = new THREE.Mesh(wallGeometry0, this.wallMaterial);
roomElement.object3D.add(mesh);
}
// ceiling ----------------------------------------------------------------------------------------------------------
let ceilingGeo = new THREE.PlaneGeometry(40, 40);
ceilingGeo.rotateX(Math.PI/2);
ceilingGeo.translate(20, 1, 20);
let ceilingMat = new THREE.MeshStandardMaterial();
let ceiling = new THREE.Mesh(ceilingGeo, ceilingMat);
let ceilingEntity = document.getElementById("ceilingEntity");
ceilingEntity.setObject3D( "mesh", ceiling );
// minimap ---------------------------------------------------------------------------------------------------------
this.canvas = document.getElementById("minimapCanvas");
this.minimapContext = this.canvas.getContext("2d");
this.minimapPlane = document.getElementById("minimapPlane");
this.rainbowQuest.drawMap(this.minimapContext);
this.minimapPlane.getObject3D('mesh').material.map.needsUpdate = true;
this.minimapMarker = document.getElementById("minimapMarker");
this.minimapMarker.object3D.position.set(1,0,0);
// TODO: try to reduce attribute calls to reduce context lost?
this.pos = new THREE.Vector3();
this.cameraDirection = new THREE.Vector3();
this.cameraAngle = 0;
this.markerScale = 1;
// place orbs ------------------------------------------------------------------------------------------------------
let orbColors = [null, "red", "orange", "yellow", "green", "blue", "violet"];
let orbModels = [null, "#heartModel", "#flameModel", "#sunModel", "#cloverModel", "#waterModel", "#moonModel"];
let orbArray = [null];
// rainbow orbs
for (let i = 1; i <= 6; i++)
{
let room = this.rainbowQuest.roomArray[i];
let orb = document.createElement("a-entity");
orb.setAttribute("position", {x: room.centerX + 0.5, y: 0.5, z: room.centerY + 0.5});
orb.setAttribute("orb", `id: ${i}; modelSrc: ${orbModels[i]}; color: ${orbColors[i]}; minimapX: ${-0.5 + 0.2*(i-1)};`);
this.el.appendChild(orb);
orbArray.push(orb);
}
// negative orbs
for (let i = 7; i <= 12; i++)
{
let room = this.rainbowQuest.roomArray[i];
let orb = document.createElement("a-entity");
orb.setAttribute("position", {x: room.centerX + 0.5, y: 0.5, z: room.centerY + 0.5});
orb.setAttribute("orb", `id: ${i}; modelSrc: #lightningModel; color: #222222; minimapX: 0;`);
this.el.appendChild(orb);
orbArray.push(orb);
}
this.orbsCollected = 0;
this.el.sceneEl.addEventListener("orb-collected", function (eventData) {
self.orbsCollected++;
if (self.orbsCollected <= 6)
{
// camera flash with room color
self.startFade( orbColors[eventData.detail.id] );
self.audioSparkle.play();
// depending on eventData.detail.id, something else happens in game
}
if (self.orbsCollected == 6)
{
// new raycaster beam - with the power to vanquish negativity orbs
self.beamEntity.getObject3D("mesh").material = rainbowMaterial;
for (let i = 7; i <= 12; i++)
{
// can now interact with lightning orbs
orbArray[i].classList.add("raycaster-target");
// floor/wall material for negative rooms changes
self.floorMaterial.uniforms.roomEffect.value[i] = 0;
self.wallMaterial.uniforms.roomEffect.value[i] = 0;
// update map room colors
self.updateMapRoom(i, "#777777");
}
// audio will change for dark orb rooms after this
}
if (self.orbsCollected >= 7)
{
// bright flash
self.startFade( "white" );
self.audioWhoosh.play();
// change room/wall to rainbow material
self.floorMaterial.uniforms.roomEffect.value[eventData.detail.id] = 1;
self.wallMaterial.uniforms.roomEffect.value[eventData.detail.id] = 1;
// clear room on minimap to reveal colors underneath
self.updateMapRoom(eventData.detail.id, "#000000", true);
// TODO: also change music in a cleared roon?
}
if (self.orbsCollected == 12)
{
// quest successful :)
let minimapBacking2 = document.querySelector("#minimapBacking2");
minimapBacking2.getObject3D("mesh").material = rainbowMaterial;
}
});
// set up movement controls ----------------------------------------------------------------------------------------
this.player = document.getElementById("player");
// move forward/backward, left/right, and adjust speed
this.leftAxisX = 0;
this.leftAxisY = 0;
this.leftTrigger = 0;
// turn left/right
this.rightAxisX = 0;
// listen for right trigger press & raycaster to interact with objects
// event listeners
this.leftController = document.querySelector("#left-controller");
this.rightController = document.querySelector("#right-controller");
this.player = document.querySelector("#player");
this.leftController.addEventListener('thumbstickmoved', function(event)
{ self.leftAxisX = event.detail.x;
self.leftAxisY = event.detail.y; } );
this.leftController.addEventListener('triggerchanged', function (event)
{ self.leftTrigger = event.detail.value; } );
this.rightController.addEventListener('thumbstickmoved', function(event)
{ self.rightAxisX = event.detail.x;
self.rightAxisY = event.detail.y; } );
this.moveSpeed = 1;
this.cameraDirection = new THREE.Vector3();
this.turnReady = true;
this.turnAmount = Math.PI / 4; // 45 degrees?
this.turnDirection = 1;
this.turnDuration = 0.10;
this.turnTime = 0;
this.turnInProgress = false;
// does this free up memory, prevent crash / lost context?
// this.rainbowQuest = null;
this.i = 0;
this.j = 0;
this.cell = null;
this.currentRoomId = -1;
// load audio -----------------------------------------------------------------------------------------------------
this.audioWind = new Howl({ src: ['audio/wind.ogg'], autoplay: true, loop: true, volume: 1.0 });
this.audioHeartbeat = new Howl({ src: ['audio/heartbeat.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioCampfire = new Howl({ src: ['audio/campfire.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioChimes = new Howl({ src: ['audio/chimes.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioBirds = new Howl({ src: ['audio/birds.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioRiver = new Howl({ src: ['audio/river.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioCrickets = new Howl({ src: ['audio/crickets.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioHarsh = new Howl({ src: ['audio/harsh.ogg'], autoplay: false, loop: true, volume: 1.0 });
this.audioSparkle = new Howl({ src: ['audio/sparkle.ogg'], autoplay: false, loop: false, volume: 1.0 });
this.audioWhoosh = new Howl({ src: ['audio/sparkle-whoosh.ogg'], autoplay: false, loop: false, volume: 1.0 });
this.audioOof = new Howl({ src: ['audio/oof.ogg'], autoplay: false, loop: false, volume: 0.2 });
this.currentSound = this.audioWind;
this.currentSound.play();
// better raycaster graphics -------------------------------------------------------------------------------------
// draw light beam: thin textured cylinder along raycaster direction
this.beamEntity = document.createElement("a-entity");
this.beamEntity.setAttribute("geometry",
{primitive: "cylinder", radius: 0.004, height: 1.0, segmentsHeight: 1, segmentsRadial: 6});
this.beamEntity.setAttribute("material",
{shader: "flat", src: "#raycasterGradient", transparent: true, opacity: 0.5} );
// assume raycaster component on right controller
this.rightController.appendChild(this.beamEntity);
this.xrSessionStarted = false;
// need to wait for controllers to load to adjust raycaster beam mesh
this.el.sceneEl.renderer.xr.addEventListener( 'sessionstart', function(eventData) {
self.xrSessionStarted = true;
});
// fade effect --------------------------------------------------------------------------------------------------
this.fadeInProgress = false;
this.fadeDuration = 0.50;
this.fadePercentComplete = 0;
// create sphere around camera for fade effect
this.camera = document.querySelector("#camera");
this.fadeSphere = document.createElement("a-entity");
this.fadeSphere.setAttribute("geometry",
{ primitive: "sphere", radius: 0.1, segmentsHeight: 4, segmentsWidth: 4 } );
this.fadeSphere.setAttribute("material",
{ shader: "flat", color: "black", transparent: true, opacity: 0.0, side: "back"} );
this.fadeSphere.setAttribute("visible", false);
this.camera.appendChild(this.fadeSphere);
},
startFade: function(color = "#FFFFFF")
{
this.fadeInProgress = true;
this.fadePercentComplete = 0;
this.fadeSphere.setAttribute("material", "color", color);
this.fadeSphere.setAttribute("visible", true);
},
updateMapRoom: function(roomId, color, clear=false)
{
this.rainbowQuest.updateMapRoom(this.minimapContext, roomId, color, clear);
this.minimapPlane.getObject3D('mesh').material.map.needsUpdate = true;
},
play: function()
{