-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
1026 lines (889 loc) · 25.4 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
let connectedToFirebase = false;
let username = "";
let onlines = [];
let selectTypeDOM;
// map editor
let editor = {
dummy: { img: null, r: 60 },
isShowDummy: false,
isShowRealmap: false,
isShowMinimap: false,
realMapImg: null,
minimap: null,
minimapSize: [300, 300],
mapSize: [6400, 6400],
terrainDragged: null,
terrainSelected: null,
terrainHovered: null,
pointSelected: null,
pointHovered: null,
mouse: [0, 0],
dragDeltaMouse: [0, 0],
camera: {
x: 0,
y: 0,
scale: 1,
xTo: 0,
yTo: 0,
scaleTo: 1,
},
terrains: [],
};
function preload() {
editor.dummy.img = loadImage("asset/dummy.png");
editor.realMapImg = loadImage("asset/full-minimap.png");
}
function setup() {
createCanvas(1000, 600).parent("canvasWrapper");
imageMode(CENTER);
textFont("monospace");
strokeCap(ROUND);
editor.minimap = createGraphics(editor.minimapSize[0], editor.minimapSize[0]);
selectTypeDOM = select("#terrain-type");
resetEditorCamera();
askName();
}
function draw() {
background(30);
updateCamera(editor.camera);
beginStateCamera(editor.camera);
// mouse
editor.mouse = canvasToWorld([mouseX, mouseY], editor.camera);
// real map
drawRealMap();
// style
textSize(14 / editor.camera.scale);
strokeWeight(1 / editor.camera.scale);
// draw grid
drawGrid(editor.camera);
// draw polygons
strokeWeight(3 / editor.camera.scale);
drawMap(editor);
endStateCamera();
drawMinimap();
fill("#fff9");
text(~~editor.camera.x + "," + ~~editor.camera.y, 10, 10);
}
function mouseDragged(e) {
if (!isMouseInCanvas(e)) return;
if (!editor.terrainDragged && !editor.pointSelected) {
editor.camera.xTo -= movedX / editor.camera.scale;
editor.camera.yTo -= movedY / editor.camera.scale;
}
}
function mouseMoved(e) {
if (!isMouseInCanvas(e)) return;
editor.pointHovered = null;
editor.terrainHovered = null;
// check hover terrain
editor.terrainHovered = getHoveredTerrain(editor.mouse, editor.terrains);
// check hover points in terrain
if (editor.terrainSelected) {
editor.pointHovered = getHoveredPoint(editor.mouse, editor.terrainSelected);
}
}
function mousePressed(e) {
if (!isMouseInCanvas(e)) return;
if (editor.terrainSelected) {
if (editor.pointHovered) {
editor.pointSelected = editor.pointHovered;
editor.dragDeltaMouse = [0, 0];
} else {
let pressedTerrain = getHoveredTerrain(editor.mouse, editor.terrains);
if (pressedTerrain) {
if (pressedTerrain != editor.terrainSelected) {
setTerrainSelected(pressedTerrain);
} else {
editor.terrainDragged = editor.terrainSelected;
}
}
}
}
if (!editor.pointHovered && editor.terrainHovered) {
setTerrainSelected(editor.terrainHovered);
editor.dragDeltaMouse = [
editor.terrainSelected.position[0] - editor.mouse[0],
editor.terrainSelected.position[1] - editor.mouse[1],
];
}
}
function mouseReleased(e) {
if (!isMouseInCanvas(e)) return;
if (editor.terrainSelected) {
updateTerrainFirebase(editor.terrainSelected);
}
editor.pointSelected = null;
editor.terrainDragged = null;
}
function mouseWheel(e) {
if (!isMouseInCanvas(e)) return;
if (e.delta > 0) {
if (editor.camera.scaleTo > 0.01) {
editor.camera.scaleTo -= editor.camera.scaleTo / 5;
}
} else {
if (editor.camera.scaleTo < 10) {
editor.camera.scaleTo += editor.camera.scaleTo / 5;
}
}
}
function keyPressed() {
if (key == "a") {
if (editor.terrainSelected) {
// calculate position to add
let pos = [
editor.mouse[0] - editor.terrainSelected.position[0],
editor.mouse[1] - editor.terrainSelected.position[1],
];
// add point to that position
addPointToPoly(editor.terrainSelected.polygon, pos[0], pos[1]);
// decomp polygons
editor.terrainSelected.polygons = decompPolygon(
editor.terrainSelected.polygon
);
// save to firebase
updateTerrainFirebase(editor.terrainSelected);
}
}
if (key == "d") {
if (editor.pointHovered) {
// delete point
deletePointFromPolygon(
editor.terrainSelected.polygon,
editor.pointHovered
);
// decomp polygons
editor.terrainSelected.polygons = decompPolygon(
editor.terrainSelected.polygon
);
editor.pointHovered = null;
// save to firebase
updateTerrainFirebase(editor.terrainSelected);
}
}
}
// =================== get/set =================
function setTerrainSelected(terrain) {
editor.terrainSelected = terrain;
if (terrain) selectTypeDOM.value(terrain.type || "wall");
}
// =================== real map ================
function setShowRealMap(value) {
editor.isShowRealmap = value;
}
function setShowMinimap(value) {
editor.isShowMinimap = value;
}
function changeAsset(select) {
editor.realMapImg = loadImage("asset/" + select.value);
}
function drawMinimap() {
if (editor.isShowMinimap && editor.realMapImg) {
let size = editor.minimapSize;
editor.minimap.background(10);
editor.minimap.push();
editor.minimap.translate(size[0] * 0.5, size[1] * 0.5);
editor.minimap.scale(editor.camera.scale);
editor.minimap.translate(-editor.camera.x, -editor.camera.y);
editor.minimap.image(
editor.realMapImg,
0,
0,
editor.mapSize[0],
editor.mapSize[1]
);
editor.minimap.pop();
image(editor.minimap, width - size[0] / 2, height - size[1] / 2);
stroke("blue");
noFill();
rect(width / 2 - size[0] / 2, height / 2 - size[1] / 2, size[0], size[1]);
}
}
function drawRealMap() {
if (editor.isShowRealmap && editor.realMapImg) {
image(
editor.realMapImg,
editor.mapSize[0] / 2,
editor.mapSize[1] / 2,
editor.mapSize[0],
editor.mapSize[1]
);
// fill("#3335");
// noStroke();
// rect(0, 0, editor.mapSize[0], editor.mapSize[1]);
}
}
// ===================== map ====================
function drawMap(_editor) {
// show terrains
for (let terrain of _editor.terrains) {
// flag
let isHovered = _editor.terrainHovered == terrain;
let isSelected = _editor.terrainSelected == terrain;
// polygon
drawTerrain(
terrain,
isSelected,
isSelected,
getColorBaseOnType(terrain.type, isHovered || isSelected)
);
// position
if (isHovered || isSelected) {
stroke("yellow");
noFill();
circle(terrain.position[0], terrain.position[1], 20);
}
// polygons
if (isHovered || isSelected) {
drawTerrainColor(terrain, isSelected);
}
// decomp polygon
if (isSelected && terrain.polygon.length > 3) {
terrain.polygons = decompPolygon(terrain.polygon);
}
}
// show dummy
if (editor.isShowDummy) {
image(
editor.dummy.img,
editor.camera.x,
editor.camera.y,
editor.dummy.r,
editor.dummy.r
);
}
// terrain dragged
if (_editor.terrainDragged) {
_editor.terrainDragged.position[0] =
_editor.mouse[0] + _editor.dragDeltaMouse[0];
_editor.terrainDragged.position[1] =
_editor.mouse[1] + _editor.dragDeltaMouse[1];
let p = _editor.terrainDragged.position;
let t = `[${~~p[0]},${~~p[1]}]`;
stroke("#555");
fill("yellow");
text(t, p[0], p[1]);
}
// terrain selected
// if (_editor.terrainSelected) {
// }
// terrain hovered
// if (_editor.terrainHovered) {
// }
// terrain selected
if (_editor.terrainSelected) {
if (_editor.pointSelected) {
_editor.pointSelected[0] =
_editor.mouse[0] +
_editor.dragDeltaMouse[0] -
_editor.terrainSelected.position[0];
_editor.pointSelected[1] =
_editor.mouse[1] +
_editor.dragDeltaMouse[1] -
_editor.terrainSelected.position[1];
}
// hight light hovered
if (_editor.pointHovered) {
let realPosHover = [
_editor.terrainSelected.position[0] + _editor.pointHovered[0],
_editor.terrainSelected.position[1] + _editor.pointHovered[1],
];
noFill();
stroke("yellow");
circle(realPosHover[0], realPosHover[1], 10);
}
}
}
function setShowDummy(_isShowDummy) {
editor.isShowDummy = _isShowDummy;
}
// =============== firebase ================
/*
{
id: "0",
position: "[100, 100]",
polygon: "[[-50, -50], [50, -50], [50, 50], [-50, 50]]",
polygons: "[]",
},
*/
function askName() {
let localUserName = localStorage.getItem("lol-mapeditor-2-username");
Swal.fire({
title: "Tên của bạn",
text: "Điền tên của bạn để mọi người thấy được công việc bạn đang làm",
input: "text",
inputValue: localUserName,
showCancelButton: false,
allowOutsideClick: false,
allowEscapeKey: false,
}).then((resultName) => {
if (resultName.isConfirmed && resultName.value != "") {
username = resultName.value;
localStorage.setItem("lol-mapeditor-2-username", username);
connectFirebase(username);
} else {
askName();
}
});
}
function connectFirebase(_username) {
Swal.fire({
icon: "info",
title: "Đang lấy dữ liệu..",
text: "Đang lấy dữ liệu từ firebase",
width: "100%",
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: false,
didOpen: () => {
Swal.showLoading();
},
});
initFireBase();
// connect with username
addDataFirebase("onlines/" + _username, getFormattedDate());
addDataFirebase("history/" + getFormattedDate(), "join:" + _username);
window.addEventListener("beforeunload", function (e) {
addDataFirebase("history/" + getFormattedDate(), "left:" + _username);
removeDataFirebase("onlines/", _username);
});
// listen events
listenToFireBase("onlines/", (data) => {
onlines = data;
});
listenToFireBase("terrains/", (data) => {
// hide loading
if (!connectedToFirebase) {
console.log("connected");
connectedToFirebase = true;
Swal.hideLoading();
Swal.close();
}
// get terrains data
let terrainArr = [];
for (let key in data) {
terrainArr.push({
id: data[key].id,
position: JSON.parse(data[key].position),
polygon: JSON.parse(data[key].polygon),
polygons: JSON.parse(data[key].polygons),
type: data[key].type || "wall",
});
}
editor.terrains = terrainArr;
// re select terrain
if (editor.terrainSelected) {
for (let terrain of editor.terrains) {
if (editor.terrainSelected.id == terrain.id) {
setTerrainSelected(terrain);
break;
}
}
}
});
}
function deleteTerrainFirebase(terrain) {
removeDataFirebase("terrains/", terrain.id);
}
function addTerrainFirebase(terrain) {
addDataFirebase("terrains/" + terrain.id, terrain, (error) => {
Swal.fire({
icon: "error",
title: "Lỗi",
text: "Lỗi khi lưu polygon mới vào firebase. " + error,
});
});
}
function updateTerrainFirebase(terrain) {
// chuyển về int
let positionData = terrain.position.map((value) => ~~value);
let polygonData = terrain.polygon.map((point) => [~~point[0], ~~point[1]]);
let polygonsData = terrain.polygons.map((poly) => {
let result = [];
for (let point of poly) {
result.push([~~point[0], ~~point[1]]);
}
return result;
});
// chuyển về json
let data = {
id: terrain.id,
position: JSON.stringify(positionData),
polygon: JSON.stringify(polygonData),
polygons: JSON.stringify(polygonsData),
type: terrain.type || "wall",
};
// update
updateDataFirebase("terrains/" + data.id, data);
}
// =============== UI ===================
function addTerrain() {
Swal.fire({
icon: "info",
title: "Thêm polygon",
text: "Bạn muốn tạo Polygon có mấy đỉnh",
input: "number",
inputValue: 4,
showCancelButton: true,
}).then((result) => {
if (result.isConfirmed) {
let count = result.value;
let angle = TWO_PI / count;
let radius = 50;
// https://p5js.org/examples/form-regular-polygon.html
let polygon = [];
for (let a = 0; a < TWO_PI; a += angle) {
let sx = cos(a) * radius;
let sy = sin(a) * radius;
polygon.push([~~sx, ~~sy]);
}
let newTerrain = {
id: generateNewKeyFirebase("terrains/"),
position: `[${editor.camera.x}, ${editor.camera.y}]`,
polygon: JSON.stringify(polygon), //"[[-50, -50],[50, -50],[50, 50],[-50, 50]]",
polygons: "[]",
};
// editor.terrains.push(newTerrain); // khong can
setTerrainSelected(newTerrain);
addTerrainFirebase(newTerrain);
}
});
}
function deleteSelectedTerrain() {
if (editor.terrainSelected) {
Swal.fire({
icon: "warning",
title: "Xóa polygon",
text: "Bạn có chắc muốn xóa polygon đang chọn?",
showCancelButton: true,
confirmButtonText: "Xóa",
cancelButtonText: "Hủy",
}).then((result) => {
if (result.isConfirmed) {
deleteTerrainFirebase(editor.terrainSelected);
setTerrainSelected(null);
// deleteTerrain(editor.terrainSelected, editor.terrains); // không cần xóa nữa, firebase sẽ đồng bộ
}
});
} else {
Swal.fire({
icon: "info",
title: "Lỗi",
text: "Chưa chọn polygon nào để xóa.",
});
}
}
function rotateSelectedTerrain() {
if (editor.terrainSelected) {
Swal.fire({
icon: "warning",
title: "Xoay polygon",
text: "Nhập vào góc muốn xoay (0-360, chiều kim đồng hồ)",
input: "number",
inputLabel: "Góc",
showCancelButton: true,
confirmButtonText: "Xoay",
cancelButtonText: "Hủy",
}).then((result) => {
if (result.isConfirmed) {
for (let point of editor.terrainSelected.polygon) {
let vec = createVector(point[0], point[1]);
vec.rotate(radians(result.value));
point[0] = round(vec.x);
point[1] = round(vec.y);
}
updateTerrainFirebase(editor.terrainSelected);
}
});
} else {
Swal.fire({
icon: "info",
title: "Lỗi",
text: "Chưa chọn polygon nào để xoay.",
});
}
}
function cloneSelectedTerrain() {
if (editor.terrainSelected) {
// clone
let newTerrain = JSON.parse(JSON.stringify(editor.terrainSelected));
// modify
newTerrain.id = generateNewKeyFirebase("terrains/");
newTerrain.position = JSON.stringify([
round(editor.camera.x),
round(editor.camera.y),
]);
newTerrain.polygon = JSON.stringify(newTerrain.polygon);
newTerrain.polygons = JSON.stringify(newTerrain.polygons);
addTerrainFirebase(newTerrain);
console.log(newTerrain);
} else {
Swal.fire({
icon: "info",
title: "Lỗi",
text: "Chưa chọn polygon nào để clone.",
});
}
}
function changeTypeOfSelectedTerrain(select) {
if (editor.terrainSelected) {
editor.terrainSelected.type = select.value;
updateTerrainFirebase(editor.terrainSelected);
}
}
function exportMapDataMinified() {
let wall = [];
let brush = [];
let water = [];
let turret1 = [];
let turret2 = [];
for (let terrain of editor.terrains) {
// turret
if (terrain.type == "turret1") {
turret1.push(terrain.position);
} else if (terrain.type == "turret2") {
turret2.push(terrain.position);
}
// brush, wall, water
else {
for (let poly of terrain.polygons) {
let polyData = [];
for (let point of poly) {
polyData.push([
point[0] + terrain.position[0],
point[1] + terrain.position[1],
]);
}
if (!terrain.type || terrain.type == "wall") wall.push(polyData);
else if (terrain.type == "brush") brush.push(polyData);
else if (terrain.type == "water") water.push(polyData);
}
}
}
let w = JSON.stringify(wall);
let b = JSON.stringify(brush);
let wt = JSON.stringify(water);
let t1 = JSON.stringify(turret1);
let t2 = JSON.stringify(turret2);
Swal.fire({
title: "Export map data",
input: "textarea",
inputLabel: "Dữ liệu json",
inputValue: `{"wall":${w},"brush":${b},"water":${wt},"turret1":${t1},"turret2":${t2}}`,
});
}
function exportMapDataFull() {
Swal.fire({
title: "Export map data",
input: "textarea",
inputLabel: "Dữ liệu json",
inputValue: `{"data": ${JSON.stringify(editor.terrains)}}`,
});
}
function resetEditorCamera() {
editor.camera.xTo = editor.mapSize[0] / 2;
editor.camera.yTo = editor.mapSize[1] / 2;
editor.camera.scaleTo = height / (editor.mapSize[0] + editor.mapSize[0] / 10);
}
function huongdan() {
Swal.fire({
title: "Hướng dẫn",
width: "100%",
html: `
<div style="text-align: left">
Map có nhiều vật thể có hình polygon (gọi là <u>terrain</u>) <br/>
Mỗi terrain(polygon) được tạo từ nhiều <u>đỉnh</u> <br/><br/>
<u>Click chuột</u> vào 1 polygon để bắt đầu chỉnh sửa nó.<br/>
<u>Sử dụng chuột</u> với polygon được chọn:
<ul>
<li>di chuyển vị trí (kéo thả phần bên trong terrain)</li>
<li>di chuyển các đỉnh (kéo thả đỉnh)</li>
</ul>
<u>Phím tắt</u> với polygon được chọn:
<ul>
<li>A: (add) thêm đỉnh vào terrain đang chọn tại vị trí con trỏ</li>
<li>D: (delete) xóa đỉnh (của terrain đang chọn) tại vị trí con trỏ</li>
</ul>
<u>Các nút chức năng:</u>
<ul>
<li><u>Reset camera</u>: Đưa camera về trạng thái ban đầu (vị trí 0,0 thu phóng 1)</li>
<li><u>Thêm poly</u>: Thêm 1 polygon tại giữa màn hình (mặc định có 4 đỉnh hình vuông)</li>
<li><u>Xóa poly</u>: Xóa polygon đang chọn (không thể undo)</li>
<li><u>Xoay poly</u>: Xoay polygon đang chọn 1 góc (sẽ hiện khung cho phép nhập góc)</li>
<li><u>Nhân bản poly</u>: Tạo 1 bản sao (copy+paste) của polygon đang chọn, và đặt vào giữa màn hình</li>
<li><u>Minimap</u>: Hiển thị bản đồ nhỏ hiển thị map thật của lmht bên phải</li>
<li><u>Map thật</u>: Hiển thị map thật lmht bên dưới nền</li>
</ul>
<u>Dummy: </u>
<ul>
<li>Chức năng hiện dummy sẽ hiển thị 1 tướng (ahri) ở giữa màn hình </li>
<li>Với kích thước 60px (kích thước trong lol2d)</li>
<li>Giúp so sánh kích thước giữa môi trường và tướng tốt hơn</li>
</ul>
</div>
`,
});
}
function showOnline() {
let data = "";
let count = 0;
for (let user in onlines) {
count++;
if (user != username) {
data += `<p><u>${user}</u> vào lúc ${onlines[user]}</p>`;
} else {
data += `<p><u>${user}</u>(Bạn) vào lúc ${onlines[user]}</p>`;
}
}
Swal.fire({
title: count + " người đang online",
html: data,
});
}
// ====================== camera ======================
function updateCamera(cam) {
cam.x = lerp(cam.x, cam.xTo, 0.2);
cam.y = lerp(cam.y, cam.yTo, 0.2);
cam.scale = lerp(cam.scale, cam.scaleTo, 0.2);
}
function canvasToWorld(pos, cam) {
return [
(pos[0] - width * 0.5) / cam.scale + cam.x,
(pos[1] - height * 0.5) / cam.scale + cam.y,
];
}
function beginStateCamera(cam) {
push();
translate(width * 0.5, height * 0.5);
scale(cam.scale);
translate(-cam.x, -cam.y);
}
function endStateCamera() {
pop();
}
// ===================== grid ========================
function drawGrid(cam) {
let topleft = canvasToWorld([0, 0], cam);
let bottomright = canvasToWorld([width, height], cam);
let left = topleft[0];
let top = topleft[1];
let right = bottomright[0];
let bottom = bottomright[1];
// center line
stroke("#fff9");
line(0, top, 0, bottom);
line(left, 0, right, 0);
// calculate grid size
let gridSize = 50;
while (gridSize * cam.scale < 100) {
gridSize *= 2;
}
while (gridSize * cam.scale > 200) {
gridSize = gridSize / 2;
}
// draw grid
stroke("#5559");
fill("#9995");
let i;
for (i = 0; i > left; i -= gridSize) {
line(i, top, i, bottom);
text(i, i, 0);
}
for (i = 0; i < right; i += gridSize) {
line(i, top, i, bottom);
text(i, i, 0);
}
for (i = 0; i > top; i -= gridSize) {
line(left, i, right, i);
text(i, 0, i);
}
for (i = 0; i < bottom; i += gridSize) {
line(left, i, right, i);
text(i, 0, i);
}
}
// ======================= poly ========================
function addPointToPoly(poly, x, y) {
poly.push([x, y]);
}
function deletePointFromPolygon(poly, point) {
poly.splice(poly.indexOf(point), 1);
}
function drawTerrain(
terrain,
isDrawDots = false,
isDrawIndex = false,
fillColor = "#0000"
) {
stroke("#fff9");
fill(fillColor);
if (terrain.type == "turret1" || terrain.type == "turret2") {
circle(terrain.position[0], terrain.position[1], 100);
} else {
// shape
beginShape();
for (let p of terrain.polygon) {
vertex(p[0] + terrain.position[0], p[1] + terrain.position[1]);
}
endShape(CLOSE);
// points
if (isDrawDots) {
noStroke();
fill("#f009");
for (let p of terrain.polygon) {
circle(p[0] + terrain.position[0], p[1] + terrain.position[1], 10);
}
}
// index
if (isDrawIndex) {
noStroke();
fill("#fff9");
let index = 0;
for (let p of terrain.polygon) {
text(
index,
p[0] + terrain.position[0],
p[1] + terrain.position[1] - 10
);
index++;
}
}
}
}
function drawTerrainColor(terrain, hightlight) {
if (terrain.type == "turret1" || terrain.type == "turret2") {
fill(getColorBaseOnType(terrain.type));
stroke(hightlight ? "#fff" : "#555");
circle(terrain.position[0], terrain.position[1], 100);
return;
}
let c = ["#fff5", "#0f05", "#00f5", "#f005", "#ff05", "#0ff5"];
let colorIndex = 0;
for (let poly of terrain.polygons) {
stroke("#fff9");
fill(c[colorIndex]);
// shape
beginShape();
for (let p of poly) {
vertex(p[0] + terrain.position[0], p[1] + terrain.position[1]);
}
endShape(CLOSE);
// points
if (hightlight) {
noStroke();
fill("#f009");
for (let p of poly) {
circle(p[0] + terrain.position[0], p[1] + terrain.position[1], 10);
}
}
colorIndex++;
if (colorIndex >= c.length) colorIndex = 0;
}
}
// =============== decomp polygon ================
function decompPolygon(poly) {
if (poly.length < 3) return;
// Make sure the polygon has counter-clockwise winding. Skip this step if you know it's already counter-clockwise.
decomp.makeCCW(poly);
// Decompose into convex polygons, using the faster algorithm
return decomp.quickDecomp(poly);
}
// ==================== util ===================
function getHoveredTerrain(m, terrains) {
let hovereds = [];
for (let terrain of terrains) {
// not decomp yet
if (terrain.polygons.length == 0) {
let SATvertices = terrain.polygon.map(
(point) =>
new SAT.Vector(
point[0] + terrain.position[0],
point[1] + terrain.position[1]
)
);
if (isMouseInPoly(m, SATvertices)) hovereds.push(terrain);
}
// decomped
else {
for (let poly of terrain.polygons) {
let SATvertices = poly.map(
(point) =>
new SAT.Vector(
point[0] + terrain.position[0],
point[1] + terrain.position[1]
)
);
if (isMouseInPoly(m, SATvertices)) hovereds.push(terrain);
}
}
}
let result = null;
// check if mouse is hover multiple terrain
if (hovereds.length > 0) {
result = hovereds[0];
for (let t of hovereds) {
if (result.type == "water" && t.type != "water") {
result = t;
}
}
}
return result;
}
function isMouseInPoly(m, SATvertices) {
let SATpolygon = new SAT.Polygon(new SAT.Vector(), SATvertices);
let collided = SAT.pointInPolygon(new SAT.Vector(m[0], m[1]), SATpolygon);
return collided;
}
function getHoveredPoint(m, terrain) {
let pos = terrain.position;
for (let p of terrain.polygon) {
if (dist(m[0], m[1], p[0] + pos[0], p[1] + pos[1]) < 10) {
return p;
}
}
return null;
}
function deleteTerrain(terrain, listTerrains) {
listTerrains.splice(listTerrains.indexOf(terrain), 1);
}
function getFormattedDate() {
var date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
var str = `${year}/${month}/${day}/${addZero(hour)}:${addZero(
minute
)}:${addZero(second)}`;
return str;
}
function addZero(n) {
return n < 10 ? "0" + n : n;
}
function isMouseInCanvas(event) {
return (
event.target.id == "defaultCanvas0" &&
!(mouseX < 0 || mouseX > width || mouseY < 0 || mouseY > height)