-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1131 lines (1034 loc) · 34.5 KB
/
main.js
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
/**
* This p5.js sketch creates a maze and renders it in 3D using a form of
* "raycasting" similar to the method used in Wolfenstein 3D by id Software. It
* can also display the maze from a top-down 2D map-perspective. I was inspired
* to write this after watching https://www.youtube.com/watch?v=eOCQfxRQ2pY
* and while working on my own basic ray tracing renderer.
*
* Originally written in December 2018 by Ben (quillaja).
* Live demo at: http://quillaja.net/raymaze/sketch.html
* Github: https://github.com/quillaja/raymaze
*/
/**
* The camera, which is the player's point of view.
* @type {Camera}
*/
let cam;
/**
* List of direction rays to sample.
* @type {p5.Vector[]}
*/
let dirs;
/**
* The maze information.
* @type {Grid}
*/
let grid;
/**
* Image used as the maze background.
* @type {p5.Graphics}
*/
let bg;
/**
* Mechanism to display messages on the screen for a period of time.
* @type {MessageQueue}
*/
let msgs;
// horizontal and vertical size of the maze.
// used in calcuateRenderParams()
const gridw = 15;
const gridh = 15;
// colors for wall and exit.
let wallColor;
let exitColor;
// textures for walls and exit.
const textures = {
/**
* @type {p5.Image[]}
*/
walls: [],
/**
* @type {p5.Image[]}
*/
doors: [],
};
/**
* @type {p5.Image[]}
*/
let tex;
let imagetextures;
// set in calculateRenderParams()
let scalef = 1; // scales map view
let raywidth = 0; // alters number of rays used/"resolution" of walls.
// A list of options that can be turned on and off (generally by the player).
const toggles = {
mapView: false,
hideMaze: true,
showRays: false,
viewChanged: true,
statsDisplay: false,
raysMethod: "lerp",
textures: true,
}
// object for storing program statistics.
const stats = {
fpsSum: 0,
fpsCount: 0,
msPerRay: 0,
msPerRaySum: 0,
msPerRayCount: 0,
tilesCheckedPerRay: 0,
tilesCheckedPerRaySum: 0,
tilesCheckedPerRayCount: 0,
}
/**
* load necessary resources.
*/
function preload() {
wallColor = makeGridColor(0, 200, 200); // set global wall color vars.
exitColor = makeGridColor(0, 255, 0);
tex = [];
let walls = ["img/bluebrick.gif", "img/crate.gif", "img/eye.gif", "img/guts.gif", "img/redbrick.gif", "img/whitebrick.gif"];
let doors = ["img/door0.gif", "img/door1.gif", "img/door2.gif", "img/door3.gif", "img/door4.gif"];
for (const filename of walls) {
textures.walls.push(loadImage(filename));
}
for (const filename of doors) {
textures.doors.push(loadImage(filename));
}
imagetextures = pickRandomTextures();
tex = imagetextures;
}
/**
* Set up the sketch.
*/
function setup() {
createCanvas(windowWidth, windowHeight - 5);
calculateRenderingParams();
createGridAndPlaceCam();
msgs = new MessageQueue();
msgs.add(8, "press s to toggle statistics");
msgs.add(8, "press space to toggle 3D or map view");
msgs.add(8, "press arrow keys to move");
msgs.add(8, "find the exit (green or door textured)");
}
/**
* Render the sketch.
*/
function draw() {
// move player
if (keyIsDown(LEFT_ARROW) || (mouseIsPressed && mouseX < width / 3)) {
cam.rotateCW();
}
if (keyIsDown(RIGHT_ARROW) || (mouseIsPressed && mouseX >= 2 / 3 * width)) {
cam.rotateCCW();
}
if (keyIsDown(UP_ARROW) || (mouseIsPressed && mouseY < height / 3)) {
cam.moveForward();
}
if (keyIsDown(DOWN_ARROW) || (mouseIsPressed && mouseY >= 2 / 3 * height)) {
cam.moveBackward();
}
// check and correct player intersection with walls
cam.checkCollisions(grid);
// draw view
// only draw if necessary to help maintain good framerate
if (cam.hasMoved() || toggles.viewChanged) {
background(0);
toggles.viewChanged = false;
stats.tilesCheckedPerRay = 0;
grid.unhideCell(cam.pos.x, cam.pos.y);
// Draw either the map view or 3d "raycast" view
// based on the player-controlled toggle.
if (toggles.mapView) {
// 2d map view
push();
scale(scalef, scalef);
noStroke();
for (let y = 0; y < grid.height; y++) {
for (let x = 0; x < grid.width; x++) {
if (grid.match(x, y, SOLID) ||
(toggles.hideMaze && grid.match(x, y, HIDDEN))) {
let c = vecToColor(colorFromCell(grid.cell(x, y)));
fill(c);
rect(x, y, 1, 1);
}
}
}
strokeWeight(0.01);
noFill();
// either draw the actual rays traced or a simple directional indicator.
if (toggles.showRays) {
let hit = new Hit();
for (const dir of cam.getRays(dirs)) {
stroke(0, 0, 255);
line(cam.pos.x, cam.pos.y, cam.pos.x + dir.x, cam.pos.y + dir.y);
marchRay(hit, cam.pos, dir, grid)
stroke(0, 255, 0);
ellipse(hit.pos.x, hit.pos.y, 0.1);
}
} else {
fill(0, 0, 255);
ellipse(cam.pos.x, cam.pos.y, 0.4);
stroke(0, 255, 0);
strokeWeight(0.08);
line(cam.pos.x, cam.pos.y, cam.pos.x + 0.5 * Math.cos(cam.rot), cam.pos.y + 0.5 * Math.sin(cam.rot));
}
pop();
} else {
// 3d view
push();
// draw ceiling and floor
image(bg, 0, 0);
// draw walls
rectMode(CENTER);
translate(0, height / 2);
cam.getRays(dirs); // get a list of directional rays to cast
const lookx = Math.cos(cam.rot); // calculate look direction vector
const looky = Math.sin(cam.rot);
let hit = new Hit(); // create only one Hit obj and reuse to reduce garbage generation.
for (let i = 0; i < dirs.length; i++) {
let dir = dirs[i];
marchRay(hit, cam.pos, dir, grid); // do the "raycast"
// dot product ray dir with look dir to scale d so straight lines look straight.
let d = hit.d * (dir.x * lookx + dir.y * looky);
let c = vecToColor(colorFromCell(hit.cell).div(Math.max(1, d)));
noStroke();
if (!toggles.textures) {
fill(c);
rect((i + 0.5) * raywidth, 0, raywidth, height / d);
} else {
// figure out the horizontal point in the range [0,1]
// at which to sample the texture
let sampleX = Math.abs(hit.pos.x - Math.floor(hit.pos.x));
if (sampleX < 0.001 || sampleX > 0.999) {
sampleX = Math.abs(hit.pos.y - Math.floor(hit.pos.y));
}
let blocktex;
if (cellIs(hit.cell, SOLID)) {
blocktex = tex[SOLID];
}
if (cellIs(hit.cell, EXIT)) {
blocktex = tex[EXIT];
}
imageMode(CENTER);
image(blocktex,
(i + 0.5) * raywidth, 0, raywidth, height / d,
int(sampleX * blocktex.width), 0, 1, blocktex.height);
// draw alpha modified black rects over the texture
// to simulate darkness at distance
fill(0, map(1 / d, 0, 1, 255, 0));
rect((i + 0.5) * raywidth, 0, raywidth, height / d);
}
}
pop();
}
// update and show statistics
stats.msPerRay /= dirs.length;
stats.tilesCheckedPerRay /= dirs.length;
stats.fpsSum += frameRate();
stats.fpsCount++;
stats.tilesCheckedPerRaySum += stats.tilesCheckedPerRay;
stats.tilesCheckedPerRayCount++;
stats.msPerRaySum += stats.msPerRay;
stats.msPerRayCount++;
if (toggles.statsDisplay) {
textFont("monospace");
fill(255);
textSize(15);
text("Statistics", 10, row(0));
text(`AvgFps: ${(stats.fpsSum / stats.fpsCount).toFixed(0)}`, 10, row(1));
let g = getCellCoords(cam.pos);
text(`Cell: ${g.x.toFixed(0)}, ${g.y.toFixed(0)}`, 10, row(2))
text(`Position: ${cam.pos.x.toFixed(1)}, ${cam.pos.y.toFixed(1)}`, 10, row(3));
text(`Rays: ${dirs.length}`, 10, row(4))
text(`RayWidth: ${raywidth.toFixed(1)}`, 10, row(5));
text(`TimePRms: ${stats.msPerRay.toPrecision(3)}`, 10, row(6));
text(`AvgTPRms: ${(stats.msPerRaySum / stats.msPerRayCount).toPrecision(3)}`, 10, row(7));
text(`TilesChkPR: ${stats.tilesCheckedPerRay.toPrecision(3)}`, 10, row(8));
text(`AvgTlChkPR: ${(stats.tilesCheckedPerRaySum / stats.tilesCheckedPerRayCount).toPrecision(3)}`, 10, row(9));
text(`RaysMethod: ${toggles.raysMethod}`, 10, row(10));
text(`Fov(deg): ${(cam.fov * (180 / PI)).toFixed(1)}`, 10, row(11));
}
}
// display messages
push();
textFont("monospace");
textSize(24);
textAlign(CENTER);
fill(255);
stroke(0);
msgs.show(width / 2, height - 50);
pop();
}
/**
* a simple function to calculate the y-position of text based on a "row".
* used in displaying statistics.
* @param {number} n row number
*/
function row(n) {
return 15 * (n + 1);
}
/**
* handle key presses that control toggle-able options.
*/
function keyPressed() {
if (keyCode === 32) { // space
toggles.mapView = !toggles.mapView;
toggles.viewChanged = true;
}
if (keyCode === 83) { // s key
toggles.statsDisplay = !toggles.statsDisplay;
toggles.showRays = !toggles.showRays; // TODO: piggyback for now
toggles.viewChanged = true;
}
if (keyCode === 72) { // h key
toggles.hideMaze = !toggles.hideMaze;
toggles.viewChanged = true;
}
if (keyCode === SHIFT) {
toggles.raysMethod = toggles.raysMethod == "slerp" ? "lerp" : "slerp";
}
if (keyCode === 84) { // t key
toggles.textures = !toggles.textures;
}
if (keyCode === 80) { // p key
if (tex == imagetextures) {
tex = generateTexture(wallColor, exitColor);
} else {
tex = imagetextures;
}
}
}
/**
* respond to window resized events by recalculating the rendering parameters, etc.
*/
function windowResized() {
resizeCanvas(windowWidth, windowHeight - 5, true);
calculateRenderingParams();
cam = new Camera(cam.pos.x, cam.pos.y, cam.rot); // remake camera in old position
}
/**
* set up params for doing rendering calcs
*/
function calculateRenderingParams() {
if (width > height) {
scalef = Math.ceil(height / (gridh + 1));
} else {
scalef = Math.ceil(width / (gridw + 1));
}
raywidth = Math.ceil((height / width) * (width / 300)); // apparently the KEY was h/w instead of w/h??
dirs = new Array(Math.ceil(width / raywidth));
for (let i = 0; i < dirs.length; i++) { dirs[i] = createVector(); }
bg = createBackgroundImage(width, height, 1);
}
/**
* Generate the 'bg' image used as the background (floor and ceiling) of
* the 3D view.
* @param {number} width window width
* @param {number} height window height
* @param {number} barHeight
*/
function createBackgroundImage(width, height, barHeight) {
let bg = createGraphics(width, height);
bg.background(0);
const hh = height / 2;
const maxh = hh / barHeight
for (let h = 0; h < maxh; h++) {
let c = 100 * (1 - h / maxh);
bg.fill(c);
bg.stroke(c);
bg.rect(0, hh, width, -(hh - h * barHeight)); // ceiling
bg.rect(0, hh, width, hh - h * barHeight); // floor
}
return bg;
}
/**
* Generates a wall and exit texture using perlin noise.
* @param {number} wall wall color (as cell data)
* @param {number} exit exit color (as cell data)
* @returns {p5.Image[]} the textures
*/
function generateTexture(wall, exit) {
let gentex = [];
const size = 128;
let img = createImage(size, size);
img.loadPixels();
let xoff = 0;
let xfreq = random(1, 5);
let yoff = 0;
let yfreq = random(1, 5);
let w = colorFromCell(wall);
for (let y = 0; y < img.width; y++) {
for (let x = 0; x < img.height; x++) {
let col = p5.Vector.mult(w, (noise(xoff, yoff)));
img.set(x, y, vecToColor(col));
xoff += xfreq / size;
}
yoff += yfreq / size;
xoff = 0;
}
img.updatePixels();
gentex[SOLID] = img;
img = createImage(size, size);
img.loadPixels();
for (let y = 0; y < img.width; y++) {
for (let x = 0; x < img.height; x++) {
img.set(x, y, vecToColor(colorFromCell(exit)));
}
}
img.updatePixels();
gentex[EXIT] = img;
return gentex;
}
/**
* chooses a random texture set from "textures".
* @returns {p5.Image[]} the SOLID and EXIT textures
*/
function pickRandomTextures() {
let newtex = [];
newtex[SOLID] = random(textures.walls);
newtex[EXIT] = random(textures.doors);
return newtex;
}
/**
* initialize system.
*/
function createGridAndPlaceCam() {
imagetextures = pickRandomTextures();
tex = imagetextures;
grid = new Grid(gridw, gridh, wallColor, exitColor);
let pos = findPlaceNotInWall(grid.data);
cam = new Camera(pos.x, pos.y);
}
/**
* Camera encapsulates the point of view of the player.
* Most importantly, it generates rays to cast and manages wall collision.
*/
class Camera {
/**
* create a camera.
* @param {number} x x position
* @param {number} y y position
* @param {number} rot initial angle in radians
* @param {number} fov desired field of view.
*/
constructor(x = 0, y = 0, rot = 0, fov = QUARTER_PI) {
this.pos = createVector(x, y);
this.prevPos = createVector();
this.rot = rot; //radians
this.moved = true;
this.fov = fov * (width / height); // scale ideal fov by aspect ratio
}
/**
* rotate camera counter clockwise
* @param {number} speed rotation speed
*/
rotateCCW(speed = PI / 180) {
this.rot += speed;
if (this.rot > TWO_PI) {
this.rot -= TWO_PI; // keep in [0,2PI]
}
this.moved = true;
}
/**
* rotate camera clockwise
* @param {number} speed rotation speed
*/
rotateCW(speed = PI / 180) {
this.rot -= speed;
if (this.rot < 0) {
this.rot = TWO_PI - this.rot; // keep in [0,2PI]
}
this.moved = true;
}
/**
* move camera forward
* @param {number} speed move speed
*/
moveForward(speed = 0.02) {
this.prevPos.x = this.pos.x;
this.prevPos.y = this.pos.y;
this.pos.x += Math.cos(this.rot) * speed;
this.pos.y += Math.sin(this.rot) * speed;
this.moved = true;
}
/**
* move camera backward
* @param {number} speed move speed
*/
moveBackward(speed = 0.02) {
this.moveForward(-speed);
}
/**
* check if camera has moved since the last time this method was called.
* this is used in the draw() function as part of check to redraw
* a frame or not.
*/
hasMoved() {
let temp = this.moved;
this.moved = false;
return temp;
}
/**
* generate a list of direction vectors (rays) to cast from the camera
* out into the world.
*
* The rays are an arc covering "FOV" radians and
* centered at the camera's current rotation direction (ie the direction
* the player is looking).
*
* The method can use either a vector "lerp" or
* "slerp" method to generate rays, and the user can toggle this. Usually
* "lerp" is good enough and a little faster even though "slerp" is
* technically more correct.
* @param {p5.Vector[]} directions list contents will be overwritten
*/
getRays(directions) {
// use length of directions list to determine how many to "cast"
let n = directions.length;
if (toggles.raysMethod == "lerp") { // lerp
let start = p5.Vector.fromAngle(this.rot - this.fov / 2);
let end = p5.Vector.fromAngle(this.rot + this.fov / 2);
directions[0] = start;
for (let i = 1; i <= n - 2; i++) {
directions[i].x = lerp(start.x, end.x, i / (n - 1));
directions[i].y = lerp(start.y, end.y, i / (n - 1));
directions[i].normalize();
}
directions[n - 1] = end;
return directions;
} else { //slerp(ish)
const dtheta = this.fov / (n - 1);
for (let i = 0; i < n; i++) {
let theta = (this.rot - this.fov / 2) + i * dtheta;
directions[i].x = Math.cos(theta);
directions[i].y = Math.sin(theta);
}
return directions;
}
}
/**
* Checks for wall collision, including the EXIT. Resets the maze if
* the exit is found.
* @param {Grid} grid
*/
checkCollisions(grid) {
if (grid.match(this.pos.x, this.pos.y, EXIT)) {
console.log("found exit");
createGridAndPlaceCam();
return;
}
this.correctWallViolation(grid);
}
/**
* Does the actual work of wall collision detection and correction.
* @param {Grid} grid
*/
correctWallViolation(grid) {
let wall = grid.match(this.pos.x, this.pos.y, SOLID);
if (wall) {
// inside a wall
this.pos.x = this.prevPos.x;
this.pos.y = this.prevPos.y;
}
}
}
/**
* Hit encapsulates the results of a ray hitting a wall.
*/
class Hit {
constructor() {
this.pos = createVector();
this.gridpos = createVector();
this.cell = 0;
this.d = 0;
}
}
/**
* The marchRay function uses a style of "raycasting" inspired by the
* Wolfenstein 3D game--not actual ray casting in the normal sense (intersecting
* geometries), and not ray marching (using distance functions).
*
* A ray moves across a regular grid of "walls" and
* "free space". If the grid square is free space, the position on the opposite
* side of the grid square is calculated to determine which grid square the ray
* hits next. This process repeats until a wall is hit.
*
* This is done basically by determining where the ray hits on the "horizontal"
* lines between grid cells and on the "vertical" lines between cells. The
* new position is the closest of these 2 intersection points.
*
* See this video for a good explanation of how this style of raycasting works:
* https://www.youtube.com/watch?v=eOCQfxRQ2pY
*
* @param {Hit} hit the result of the cast. will be modfied by function.
* @param {p5.Vector} dir direction of the ray to cast
* @param {p5.Vector} pos starting position of the ray (camera's location)
* @param {Grid} grid the 'world'
*/
function marchRay(hit, pos, dir, grid) {
let starttime = Date.now();
let posOrig = pos;
pos = pos.copy();
let wall = grid.match(pos.x, pos.y, SOLID);
let p1 = createVector();
let p2 = createVector();
while (!wall) {
p1.x = 0; p1.y = 0; p2.x = 0; p2.y = 0;
if (dir.x > 0) {
p1.x = Math.ceil(pos.x);
} else if (dir.x < 0) {
p1.x = Math.floor(pos.x);
}
if (dir.y > 0) {
p2.y = Math.ceil(pos.y);
} else if (dir.y < 0) {
p2.y = Math.floor(pos.y);
}
p1.y = pos.y + dir.y * ((p1.x - pos.x) / dir.x);
p2.x = pos.x + dir.x * ((p2.y - pos.y) / dir.y);
let p1len = p5.Vector.dist(pos, p1);
let p2len = p5.Vector.dist(pos, p2);
if (p1len <= p2len) {
pos.set(p1);
} else {
pos.set(p2);
}
pos.x += dir.x * 0.00000001; // offset the new position slightly
pos.y += dir.y * 0.00000001; // to ensure the 'next' cell is checked.
wall = grid.match(pos.x, pos.y, SOLID);
stats.tilesCheckedPerRay++;
}
hit.pos.set(pos);
hit.cell = grid.cell(pos.x, pos.y);
hit.d = p5.Vector.dist(posOrig, pos);
hit.gridpos = getCellCoords(pos);
stats.msPerRay += Date.now() - starttime;
return hit;
}
/**
* gets the grid cell indices from a position.
* @param {p5.Vector} pos
*/
function getCellCoords(pos) {
let gridx = Math.floor(pos.x);
let gridy = Math.floor(pos.y);
return createVector(gridx, gridy);
}
/**
* Grid encapsulates the world. Cells are represented with a 32-bit integer
* value. The lowest byte is a series of bitflags indicating things such as if
* the cell is a wall. The higher 3 bytes are used to encode the cell's color
* (or perhaps texture if I had gotten that far). So there are a lot of
* bitwise operations performed in later grid/maze manipulation functions.
*/
class Grid {
/**
* creates a new grid using wilson's maze generation algorithm.
*/
constructor(width, height, wallColor = COLOR_W, exitColor = COLOR_G) {
this.data = generateGridWilson(width, height, wallColor);
makeExteriorWalls(this.data, wallColor);
placeExit(this.data, exitColor);
hideMazePassages(this.data, wallColor);
this.height = this.data.length;
this.width = this.data[0].length;
}
/**
* Get the data associated with the cell.
* @param {number} x
* @param {number} y
* @return {number}
*/
cell(x, y) {
let gridx = Math.floor(x);
let gridy = Math.floor(y);
return this.data[gridy][gridx];
}
/**
* Checks if the cell has the given flags set.
* @param {number} x
* @param {number} y
* @param {number} flags set of bitflags to test against the cell
*/
match(x, y, flags) {
return cellIs(this.cell(x, y), flags);
}
/**
* unsets the "hidden" flag for the cell.
* @param {number} x
* @param {number} y
*/
unhideCell(x, y) {
let gridx = Math.floor(x);
let gridy = Math.floor(y);
this.data[gridy][gridx] &= ~HIDDEN; // unset hidden flag.
}
}
/**
* Does the actual work of checking bitflags.
* @param {number} cell cell's data
* @param {number} flags bitflags to check
*/
function cellIs(cell, flags) {
return (cell & flags) == flags;
}
/**
* This basically just goes around the edge of the grid and makes every
* cell solid.
* @param {number[][]} grid the 'world' grid in raw data form
*/
function makeExteriorWalls(grid, color) {
for (let y = 0; y < grid.length; y++) {
if (y == 0 || y == grid.length - 1) {
for (let x = 0; x < grid[y].length; x++) {
grid[y][x] = SOLID | color;
}
} else {
grid[y][0] = SOLID | color;
grid[y][grid[y].length - 1] = SOLID | color;
}
}
}
/**
* This basically sets the 'hidden' flag on all non-wall cells.
* @param {number[][]} grid the 'world' grid in raw data form
*/
function hideMazePassages(grid, wallColor) {
// TODO: i could just set and unset the color. better? worse?
for (let y = 1; y < grid.length - 1; y++) {
for (let x = 1; x < grid[y].length - 1; x++) {
if (!cellIs(grid[y][x], SOLID)) {
grid[y][x] |= HIDDEN | wallColor;
}
}
}
}
/**
* places the exit in a wall in a random location that is guaranteed to be
* accessible to the player.
* @param {number[][]} grid the 'world' grid in raw data form.
* @param {number} color color of the exit
*/
function placeExit(grid, color) {
// start not in wall. take random walk until hitting a wall.
let pos = findPlaceNotInWall(grid);
let inWall = false;
while (!inWall) {
takeRandomStep(pos);
inWall = cellIs(grid[Math.floor(pos.y)][Math.floor(pos.x)], SOLID);
}
grid[Math.floor(pos.y)][Math.floor(pos.x)] = EXIT | color;
}
/**
* Steps through each position and generates a grid cell with the value
* returned from function "f".
* @param {number} w width of grid
* @param {number} h height of grid
* @param {number} wallColor
* @param {(x,y,w,h,wc)=>number} f function returning the cell data given the x,y grid position
* @returns {number[][]}
*/
function generateGridRandom(w, h, wallColor,
f = (x, y, w, h, wc) => Math.random() < 0.2 ? SOLID | wc : NONE) {
let grid = new Array(h);
for (let y = 0; y < h; y++) {
grid[y] = new Array(w);
for (let x = 0; x < w; x++) {
grid[y][x] |= f(x, y, w, h, wallColor);
}
}
return grid;
}
/**
* generates a grid completely of walls
* @param {number} w width
* @param {number} h height
* @param {number} wallColor
*/
function generateSolidGrid(w, h, wallColor) {
let grid = new Array(h);
for (let y = 0; y < grid.length; y++) {
grid[y] = new Array(w);
for (let x = 0; x < grid[y].length; x++) {
grid[y][x] = SOLID | wallColor;
}
}
return grid;
}
/**
* Generates a grid of random walks which may overlap. This is like a worm
* eating out passages in a block of wood.
* @param {number} w width
* @param {number} h height
* @param {number} wallColor
* @param {number} walkLen length of the random walks to take
* @param {number} numWalks the number of random walks to take
*/
function generateGridRandomWalks(w, h, wallColor, walkLen, numWalks) {
// create grid completely solid
let grid = generateSolidGrid(w, h, wallColor);
// carve out numWalks random walks
for (let n = 0; n < numWalks; n++) {
let pos = createVector(Math.floor(random(1, w)), Math.floor(random(1, h)));
for (let step = 0; step < walkLen; step++) {
grid[pos.y][pos.x] = NONE;
takeRandomStep(pos);
pos.x = constrain(pos.x, 1, w - 1);
pos.y = constrain(pos.y, 1, h - 1);
}
}
return grid;
}
/**
* Create a grid/maze using Wilson's Algorithm.
*
* Wilson's basically creates a maze by taking acyclic random walks that
* start in a "wall" part of the maze and end in a "passage" part of the maze.
* For a good description of the algorithm, see:
* http://weblog.jamisbuck.org/2011/1/20/maze-generation-wilson-s-algorithm
* @param {number} w width
* @param {number} h height
* @param {number} wallColor
*/
function generateGridWilson(w, h, wallColor) {
// flags for maze (top, right, bottom, left)
const T = 1;
const R = 2;
const B = 4;
const L = 8;
const IN = 16; // in maze (aka already added)
// create completely solid maze
const mw = Math.floor(w / 2);
const mh = Math.floor(h / 2);
let maze = new Array(mh);
for (let y = 0; y < mh; y++) {
maze[y] = new Array(mw);
for (let x = 0; x < mw; x++) {
maze[y][x] = T | R | B | L; // set all 'walls'
}
}
// 0. choose inital place not IN to set to IN
let notIn = () => randPosPredicate(maze, true, (x, y) => (maze[y][x] & IN) == 0);
let pos = notIn();
maze[pos.y][pos.x] |= IN;
let visted = [];
while ((pos = notIn()) != undefined) {
// 1. choose a random place in maze not IN, add to visited
visted.push(pos.copy());
let takingAWalk = true;
while (takingAWalk) {
// 2. take random walk, keeping list of visited cells
takeRandomStep(pos);
pos.x = constrain(pos.x, 0, mw - 1); // don't leave maze
pos.y = constrain(pos.y, 0, mh - 1);
visted.push(pos.copy());
// 3. if visit a cell that is IN, stop
if ((maze[pos.y][pos.x] & IN) == IN) {
takingAWalk = false;
} else {
// 3.5 if visit a previously visted cell, delete the loop from the list
let prev = visted.findIndex((p) => pos.x == p.x && pos.y == p.y);
if (prev > -1 && prev < visted.length - 1) {
visted = visted.slice(0, prev + 1); // keep 0-prev. discards looped walk path
}
}
}
// 4. use the generated list of visited cells to 'carve' path. set cells as IN.
for (let i = 1; i < visted.length; i++) {
let d = p5.Vector.sub(visted[i], visted[i - 1]);
let x = visted[i].x;
let y = visted[i].y;
// remove walls. maze[0][0] is in "top left"
if (d.x == 0 && d.y == 1) { // moved down
maze[y][x] &= ~T;
maze[y - d.y][x - d.x] &= ~B;
} else if (d.x == 0 && d.y == -1) { // moved up
maze[y][x] &= ~B;
maze[y - d.y][x - d.x] &= ~T;
} else if (d.x == 1 && d.y == 0) { // moved right
maze[y][x] &= ~L;
maze[y - d.y][x - d.x] &= ~R;
} else if (d.x == -1 && d.y == 0) { // moved left
maze[y][x] &= ~R;
maze[y - d.y][x - d.x] &= ~L;
}
// set IN
maze[y][x] |= IN;
maze[y - d.y][x - d.x] |= IN;
}
// 5. go to 1
visted = []; // clear array
}
// convert maze to grid by asking for a wide solid grid, then carving out
// grid cells where according to the connected cells in the maze.
// simple func to convert a maze index to a 'grid' index
// grid_index = maze_index*2 + 1
let gi = (mi) => (mi * 2) + 1;
let grid = generateSolidGrid(gi(mw), gi(mh), wallColor);
for (let y = 0; y < mh; y++) {
for (let x = 0; x < mw; x++) {
// carve out the current part of the maze
grid[gi(y)][gi(x)] = NONE;
// cut out appropriate adjacent walls
if ((maze[y][x] & T) == 0) {
grid[gi(y) - 1][gi(x)] = NONE;
}
if ((maze[y][x] & B) == 0) {
grid[gi(y) + 1][gi(x)] = NONE;
}
if ((maze[y][x] & R) == 0) {
grid[gi(y)][gi(x) + 1] = NONE;
}
if ((maze[y][x] & L) == 0) {
grid[gi(y)][gi(x) - 1] = NONE;
}
}
}
return grid;
}
/**
* Moves pos a step in the x or y direction (not diagonally)
* @param {p5.Vector} pos
*/
function takeRandomStep(pos, stepsize = 1) {
switch (Math.floor(random(4))) {
case 0:
pos.x += stepsize;
break;
case 1:
pos.x -= stepsize;
break;
case 2:
pos.y += stepsize;
break;
case 3:
pos.y -= stepsize;
break;
}
return pos;
}
/**
* finds a random location that is not in a wall by making a list