-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
2402 lines (2289 loc) Β· 80.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
const TOOL_SELECT = "TOOL_SELECT";
const TOOL_ADD_POINTS = "TOOL_ADD_POINTS";
const TOOL_ADD_POINTS_QUICKLY = "TOOL_ADD_POINTS_QUICKLY";
const TOOL_ADD_BALL = "TOOL_ADD_BALL";
const TOOL_ADD_ROPE = "TOOL_ADD_ROPE";
const TOOL_ADD_DOLL = "TOOL_ADD_DOLL";
const TOOL_PRECISE_CONNECTOR = "TOOL_PRECISE_CONNECTOR";
const TOOL_GLUE = "TOOL_GLUE";
const TOOL_DRAG = "TOOL_DRAG";
const tools = [
{
id: TOOL_DRAG,
name: "Drag Points",
shortcut: "D",
tooltip: "Drag stuff around. Works when paused or playing. You can also use Right Click as a shortcut. Hold Shift before dragging to drag multiple points you can drag a selection)."
},
{
id: TOOL_ADD_POINTS,
name: "Add Points",
shortcut: "A",
tooltip: "Click anywhere to add a point. Hold Shift to make fixed points."
},
{
id: TOOL_ADD_POINTS_QUICKLY,
name: "Add Points Quickly",
shortcut: "Q",
tooltip: "Create many unconnected points. Hold Shift to make fixed points."
},
{
id: TOOL_ADD_ROPE,
name: "Make Rope",
shortcut: "R",
tooltip: "Create a connected series of points. Hold Shift to make fixed points."
},
{
id: TOOL_ADD_BALL,
name: "Make Ball",
shortcut: "B",
tooltip: "Create balls and polygons. Move the mouse up and down to choose the size, and left and right to choose the number of points. Hold Shift to make sturdier balls (where the connections vary in target length)."
},
{
id: TOOL_ADD_DOLL,
name: "Make Ragdoll",
shortcut: "L",
tooltip: "Create humanoids.",
},
{
id: TOOL_GLUE,
name: "Glue",
shortcut: "G",
tooltip: "Connect any points near the mouse to each other."
},
{
id: TOOL_PRECISE_CONNECTOR,
name: "Precise Connector",
shortcut: "C",
tooltip: "Drag from one point to another to connect them, or if theyβre already connected, to delete the connection. Hold Shift to create arbitrary-length connections."
},
{
id: TOOL_SELECT,
name: "Select",
shortcut: "S",
tooltip: "Drag to select points within a rectangle, then Copy (Ctrl+C) and Paste (Ctrl+V) or Delete (Delete). You can also drag the selected points together."
},
];
// Note: some keyboard shortcuts are handled with `keys` state (for continuous effects).
// Note: aria-keyshortcuts should be kept in sync.
const keyboardShortcuts = [
{ modifiers: ["CtrlCmd"], code: "KeyZ", action: undo, enable: () => undos.length > 0 },
{ modifiers: ["CtrlCmd"], code: "KeyY", action: redo, enable: () => redos.length > 0 },
{ modifiers: ["CtrlCmd", "Shift"], code: "KeyZ", action: redo, enable: () => redos.length > 0 },
{ modifiers: ["CtrlCmd"], code: "KeyC", action: copySelected, enable: () => selection.points.length > 0 },
{ modifiers: ["CtrlCmd"], code: "KeyX", action: cutSelected, enable: () => selection.points.length > 0 },
{ modifiers: ["CtrlCmd"], code: "KeyV", action: paste, enable: () => !!serializedClipboard },
{ modifiers: ["CtrlCmd"], code: "KeyA", action: selectAll, enable: () => points.length > 0 },
{
modifiers: ["CtrlCmd"], code: "KeyD", action: deselect,
enable: () => selection.points.length > 0 || selection.connections.length > 0,
},
{ modifiers: [], code: "Delete", action: deleteSelected },
{ modifiers: [], code: "KeyP", action: togglePlay },
{ modifiers: [], code: "F1", action: () => windowToggles.help.toggleWindow() },
// Glue selected points together without selecting the Glue tool.
// This handled elsewhere except for creating an undo state.
{ modifiers: [], code: "Space", action: undoable },
// Add points without selecting the Add Points tool.
{ modifiers: [], code: "Period", action: add_point_at_mouse_undoable },
{ modifiers: ["Shift"], code: "Period", action: add_point_at_mouse_undoable },
{ modifiers: [], code: "NumpadDecimal", action: add_point_at_mouse_undoable },
// Shift+NumpadDecimal may not work because it sends "Delete" instead, but itβs awkward to use anyways.
{ modifiers: ["Shift"], code: "NumpadDecimal", action: add_point_at_mouse_undoable },
];
// Add keyboard shortcuts for selecting tools.
for (const tool of tools) {
keyboardShortcuts.push({
modifiers: [], code: `Key${tool.shortcut}`, action: () => {
selectTool(tool.id);
}
});
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
// world state
var connections = [];
var points = [];
// interaction state
var mouse = { x: 0, y: 0, d: 0, pointerId: -1 };
var mousePrevious = { x: 0, y: 0, d: 0, pointerId: -1 };
var keys = {};
var selectedTool = TOOL_ADD_POINTS;
var lastRopePoint = null;
var connectorToolPoint = null;
var ballToolStates = []; // {ball, startPos, pointerPos,pointerId}
var dragStates = []; // {dragging, dragOffsets, pointerPos, pointerId}
var rmbDragState = null;
var selection = {
points: [],
connections: []
};
var undos = [];
var redos = [];
var serializedClipboard = null;
// tool parameters
const mouseDragForce = 0.1;
const mouseDragDampingFactor = 0.5;
const mouseDragLerpDistance = 30;
const dragMaxDistToSelect = 100; // for picking points to drag
const preciseConnectorMaxDistToSelect = 60; // for picking points to connect
const glueMaxDistToMouse = 30;
const glueMaxDistBetweenPoints = 50;
const autoConnectMaxDist = 50;
// options
var play = true;
var collision = false;
var slowmo = false; // TODO: generalize to a time scale
var autoConnect = false;
var gravity = 0.1;
var terrainEnabled = false;
var audioEnabled = false;
var audioStyle = 1;
var audioViz = false;
var ghostTrails = 0;
var windowTheme = "sandbox-theme"; // global used by index.html, and used as ID for <link>
// debug
var debugPolygons = []; // reset per frame
var debugLines = []; // reset per frame
// derived state for performance optimization
// Note: `groups` is computed manually when needed, at most once per frame (with a flag)
var groups = new Map(); // point to group id, for connected groups (used for avoiding self-collision)
var groupsComputedThisFrame = false;
// audio (initialized later)
var actx; // AudioContext
var oscillator; // OscillatorNode
var gain; // GainNode
var creakBuffer; // AudioBuffer used for creaking wood noise
var creakDist = 30; // distance from last creak
// windows
var $optionsWindow;
var $toolsWindow;
var $helpWindow;
var $aboutWindow;
var $todoWindow;
function serialize(points, connections, isSelection) {
// Note: if I ever change this to JSON,
// I should bump the version to >2, since ARSON stringifies as JSON but with values as indices,
// and formatVersion ends up looking like `formatVersion:2`
// Also donβt reorder these keys, because that could make it `formatVersion:<some other number>`
// That said, this is just a toy, and thereβs no actual import/export feature.
return ARSON.stringify({
format: "pbj-sandbox",
formatVersion: 0.1,
isSelection: !!isSelection,
points: points,
connections: connections
});
}
function deserialize(serialized) {
return ARSON.parse(serialized);
}
function getState() {
return serialize(points, connections);
}
function setState(serialized) {
var state = deserialize(serialized);
points = state.points;
connections = state.connections;
deselect();
}
function undoable() {
undos.push(getState());
redos = [];
}
function undo() {
if (undos.length < 1) return false;
redos.push(getState());
setState(undos.pop());
return true;
}
function redo() {
if (redos.length < 1) return false;
undos.push(getState());
setState(redos.pop());
return true;
}
function selectAll() {
selection.points = Array.from(points);
selection.connections = Array.from(connections);
}
function deselect() {
selection.points = [];
selection.connections = [];
}
function copySelected() {
serializedClipboard = serialize(selection.points, selection.connections, true);
}
function cutSelected() {
// undoable is in deleteSelected()
copySelected();
deleteSelected();
}
function deletePoints(pointsToDelete) {
// (no undoable! maybe I should indicate this in the function names somehow)
for (var i = pointsToDelete.length - 1; i >= 0; i--) {
var p = pointsToDelete[i];
for (var j = connections.length - 1; j >= 0; j--) {
var c = connections[j];
if (c.p1 === p || c.p2 === p) {
connections.splice(j, 1);
}
}
points.splice(points.indexOf(p), 1);
}
}
function deleteSelected() {
undoable();
deletePoints(selection.points);
deselect();
}
function paste() {
undoable();
var clipboard = deserialize(serializedClipboard);
var minX = Infinity, minY = Infinity;
for (var i = 0; i < clipboard.points.length; i++) {
var p = clipboard.points[i];
minX = Math.min(minX, p.x);
minY = Math.min(minY, p.y);
}
for (var i = 0; i < clipboard.points.length; i++) {
var p = clipboard.points[i];
p.x -= minX - mouse.x;
p.y -= minY - mouse.y;
}
points = points.concat(clipboard.points);
connections = connections.concat(clipboard.connections);
}
function togglePlay() {
play = !play;
document.getElementById("play-checkbox").checked = play;
}
function main() {
canvas.addEventListener("contextmenu", function (e) { e.preventDefault(); });
addEventListener("keydown", function (e) {
if (e.defaultPrevented) {
return;
}
if (
document.activeElement instanceof HTMLInputElement ||
document.activeElement instanceof HTMLTextAreaElement ||
!window.getSelection().isCollapsed
) {
return; // donβt prevent interaction with inputs or textareas, or copying text in windows
}
keys[e.key] = true;
keys[e.code] = true;
// console.log(`key "${e.key}", code "${e.code}", keyCode ${e.keyCode}`);
let matched = false;
for (const shortcut of keyboardShortcuts) {
if (
(
shortcut.modifiers.includes("CtrlCmd") ? (
e.ctrlKey || e.metaKey
) : (
e.ctrlKey === shortcut.modifiers.includes("Ctrl") &&
e.metaKey === shortcut.modifiers.includes("Meta")
)
) &&
e.shiftKey === shortcut.modifiers.includes("Shift") &&
e.altKey === shortcut.modifiers.includes("Alt") &&
(
("code" in shortcut && e.code === shortcut.code) ||
("key" in shortcut && e.key === shortcut.key) ||
("keyCode" in shortcut && e.keyCode === shortcut.keyCode)
) &&
(shortcut.repeatable || !e.repeat) &&
(typeof shortcut.enable === "function" ? shortcut.enable() : (shortcut.enable ?? true))
) {
e.preventDefault();
shortcut.action();
// console.log("Triggered shortcut:", shortcut);
matched = true;
break;
}
}
// if (!matched) {
// console.log("No shortcut matched:", e);
// }
});
addEventListener("keyup", function (e) { delete keys[e.key]; delete keys[e.code]; });
addEventListener("blur", function (e) { keys = {}; }); // prevents stuck keys, especially Shift when switching tabs with Ctrl+Shift+Tab (also Ctrl+Shift+T, Ctrl+Shift+N, etc.)
var deselectTextAndBlur = function () {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
document.activeElement.blur();
};
var toWorldCoords = function (pageX, pageY) {
var rect = canvas.getBoundingClientRect();
return {
x: pageX - rect.left,
y: pageY - rect.top,
};
};
var updateMouse = function ({ pageX, pageY, pointerId }) {
const mousePos = toWorldCoords(pageX, pageY);
mouse.x = mousePos.x;
mouse.y = mousePos.y;
mouse.pointerId = pointerId;
};
canvas.style.touchAction = "none";
canvas.addEventListener("pointerdown", function (e) {
updateMouse(e);
if (e.button == 0) {
mouse.left = true;
} else {
mouse.right = true;
}
if (e.button == 0) {
if (selectedTool === TOOL_DRAG) {
startDrag(toWorldCoords(e.pageX, e.pageY), e.pointerId);
} else if (selectedTool === TOOL_ADD_BALL) {
undoable();
ballToolStates.push({
ball: null,
startPos: toWorldCoords(e.pageX, e.pageY),
pointerPos: toWorldCoords(e.pageX, e.pageY),
pointerId: e.pointerId,
});
}
}
e.preventDefault();
deselectTextAndBlur();
});
addEventListener("pointerup", function (e) {
if (e.button == 0) {
mouse.left = false;
} else {
mouse.right = false;
}
for (const dragState of dragStates) {
if (dragState.pointerId === e.pointerId) {
dragStates.splice(dragStates.indexOf(dragState), 1);
}
}
for (const ballToolState of ballToolStates) {
if (ballToolState.pointerId === e.pointerId) {
ballToolStates.splice(ballToolStates.indexOf(ballToolState), 1);
}
}
e.preventDefault();
});
addEventListener("pointercancel", function (e) {
if (e.button == 0) {
mouse.left = false;
} else {
mouse.right = false;
}
e.preventDefault();
});
addEventListener("pointermove", function (e) {
updateMouse(e);
for (const dragState of dragStates) {
if (dragState.pointerId === e.pointerId) {
dragState.pointerPos = toWorldCoords(e.pageX, e.pageY);
}
}
for (const ballToolState of ballToolStates) {
if (ballToolState.pointerId === e.pointerId) {
ballToolState.pointerPos = toWorldCoords(e.pageX, e.pageY);
}
}
}, false);
/*(onresize = function () {
//canvas.width=document.body.clientWidth;
//canvas.height=document.body.clientHeight;
canvas.width = innerWidth;
canvas.height = innerHeight - 5;
step();
})();*/
setInterval(step, 15);
// shoopen = 0;
try {
actx = new AudioContext();
actx.suspend();
/*
var x, node, freq = 440;
if (actx.createScriptProcessor) {
node = actx.createScriptProcessor(1024, 1, 1);
} else {
node = actx.createJavaScriptNode(1024, 1, 1);
}
node.onaudioprocess = function (e) {
for (var i = 0; i < points.length; i++) {
var p = points[i];
shoopen += p.x + p.y;
}
//console.log(shoopen);
shoopen = Math.abs(shoopen) % 255;
var data = e.outputBuffer.getChannelData(0);
for (var i = 0; i < data.length; i++) {
data[i] = Math.sin(x * freq) * 35
+ shoopen * Math.random() * 0.001
+ Math.sin(x / 4.02) * shoopen * 0.01;
x++;
}
};
node.connect(actx.destination);
// node.start ? node.start() : node.noteOn(0);
*/
gain = actx.createGain();
gain.gain.setValueAtTime(0, actx.currentTime);
gain.connect(actx.destination);
oscillator = actx.createOscillator();
oscillator.type = "square";
oscillator.frequency.setValueAtTime(440, actx.currentTime); // value in hertz
oscillator.connect(gain);
oscillator.start();
creakBuffer = actx.createBuffer(1, actx.sampleRate, actx.sampleRate);
const data = creakBuffer.getChannelData(0);
// for (var i = 0; i < data.length; i++) {
// data[i] =
// ((Math.random() * 2 - 1) * Math.pow((i - data.length) / actx.sampleRate, 2) / 10) +
// // sand noise
// // ((Math.random() * 2 - 1) * Math.pow((i - data.length) / actx.sampleRate, 2) / 10);
// 0;
// }
// generate pink noise
const s = { b0: 0, b1: 0, b2: 0, b3: 0, b4: 0, b5: 0, b6: 0 };
for (var i = 0; i < data.length; i++) {
let white = Math.random() * 2 - 1;
s.b0 = 0.99886 * s.b0 + white * 0.0555179;
s.b1 = 0.99332 * s.b1 + white * 0.0750759;
s.b2 = 0.96900 * s.b2 + white * 0.1538520;
s.b3 = 0.86650 * s.b3 + white * 0.3104856;
s.b4 = 0.55000 * s.b4 + white * 0.5329522;
s.b5 = -0.7616 * s.b5 - white * 0.0168980;
data[i] = s.b0 + s.b1 + s.b2 + s.b3 + s.b4 + s.b5 + s.b6 + white * 0.5362;
data[i] *= 0.11;
// just messing around with the sound
// for (var j = 0; j < 6; j++) {
// s["b" + j] *= Math.sin(i * 0.001 + j * 5.1);
// }
s.b6 = white * 0.115926;
}
// made it decay and add some sine waves
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < 10; j++) {
data[i] += Math.sin(i / actx.sampleRate * 51 * (j * 2.1 + 50)) * 0.1;
}
data[i] *= Math.pow(1 - (i / data.length), 20) / 10;
}
// tiny metal tink / zipper noise
// creakBuffer = actx.createBuffer(1, actx.sampleRate, actx.sampleRate);
// const data = creakBuffer.getChannelData(0);
// for (var i = 0; i < data.length; i++) {
// data[i] +=
// // ((Math.sin(i/actx.sampleRate*460000) * 2 - 1) * Math.pow((i - data.length) / actx.sampleRate, 30) / 10) +
// // sand noise
// ((Math.random() * 2 - 1) * Math.pow(1 - i / data.length, 2) / 20);
// // 0;
// }
} catch (e) {
audioSetupError = e;
console.warn(e);
}
}
function drawArrow(ctx, x, y, angle, length, headSize = 10) {
ctx.beginPath();
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.moveTo(0, 0);
ctx.lineTo(0, -length);
ctx.moveTo(-headSize, -length + headSize);
ctx.lineTo(0, -length);
ctx.lineTo(headSize, -length + headSize);
ctx.restore();
ctx.stroke();
}
function toolDraw(ctx, intent, dragging, bold, p1, p2) {
// Highlight a point or line segment for Precise Connector, Glue, and Drag tools.
// `intent` can be "disconnect", "connect", "connect-varying-length", or "drag"
ctx.save();
const alpha = bold ? 1 : dragging ? 0.7 : 0.5;
ctx.strokeStyle =
intent === "disconnect" ? `rgba(255, 0, 0, ${alpha})` :
intent === "connect-varying-length" ?
`rgba(255, 255, 0, ${alpha})` :
`rgba(0, 255, 200, ${alpha})`;
if (p1) {
ctx.lineWidth = bold ? 2 : 1;
ctx.beginPath();
ctx.arc(p1.x, p1.y, 5, 0, 2 * Math.PI);
ctx.stroke();
}
if (p2) {
ctx.lineWidth = bold ? 2 : 1;
ctx.beginPath();
ctx.arc(p2.x, p2.y, 5, 0, 2 * Math.PI);
ctx.stroke();
}
if (p1 && p2) {
if (intent === "disconnect") {
ctx.lineWidth = 4; // has to be visible together with the existing connectionβs line
} else {
ctx.lineWidth = bold ? 2 : 1;
}
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
}
ctx.restore();
}
function computeGroups() {
// find connected groups of points
groups.clear();
for (var i = points.length - 1; i >= 0; i--) {
var p = points[i];
groups.set(p, i);
}
for (var i = connections.length - 1; i >= 0; i--) {
var c = connections[i];
var g1 = groups.get(c.p1);
var g2 = groups.get(c.p2);
if (g1 != g2) {
for (var j = points.length - 1; j >= 0; j--) {
if (groups.get(points[j]) == g2) {
groups.set(points[j], g1);
}
}
}
}
}
function areConnected(p1, p2) {
if (p1.fixed && p2.fixed) return false;
return groups.get(p1) == groups.get(p2);
}
function areDirectlyConnected(p1, p2, connections) {
// if the groups are already connected, using that information could be an optimization
// but not in this function if `connections` is an argument!
// if (groupsComputedThisFrame && !areConnected(p1, p2)) return false;
for (const connection of connections) {
if (connection.p1 == p1 && connection.p2 == p2) return true;
if (connection.p1 == p2 && connection.p2 == p1) return true;
}
return false;
}
function countConnections(point) {
let count = 0;
for (const connection of connections) {
if (connection.p1 === point) count++;
if (connection.p2 === point) count++;
}
return count;
}
function findClosestPoint(x, y, maxDistance = Infinity) {
let closestPoint = null;
let closestDist = maxDistance;
for (const point of points) {
const distance = Math.hypot(x - point.x, y - point.y);
if (distance < closestDist) {
closestDist = distance;
closestPoint = point;
}
}
return closestPoint;
}
function startDrag({ x, y }, pointerId) {
const nearToMouse = findClosestPoint(x, y, dragMaxDistToSelect);
if (nearToMouse) {
undoable();
let dragging = [nearToMouse];
// select all connected points with Shift
if (keys.Shift) {
if (!groupsComputedThisFrame) {
computeGroups();
groupsComputedThisFrame = true;
}
dragging = points.filter(p => groups.get(p) === groups.get(nearToMouse));
}
// if thereβs a selection, drag the whole selection
if (selection.points.includes(nearToMouse)) {
dragging = Array.from(selection.points);
}
let dragOffsets;
if (dragging.length === 1) {
dragOffsets = [{ x: 0, y: 0 }];
} else {
dragOffsets = dragging.map(p => ({
x: p.x - x,
y: p.y - y,
}));
}
dragStates.push({
dragging,
dragOffsets,
pointerId,
pointerPos: { x, y },
});
}
}
function step() {
// Drawing setup
if (canvas.width != innerWidth || canvas.height != innerHeight) {
canvas.width = innerWidth;
canvas.height = innerHeight;
// Clear to black immediately (initially and on resize), for ghost trails mode
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// Clear, or partially clear, leaving a trail.
// If paused with ghost trails enabled, donβt clear at all.
const alpha = play ? Math.pow(1 - ghostTrails, 4) : (ghostTrails > 0 ? 0 : 1);
ctx.fillStyle = `rgba(0,0,20,${alpha})`;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = 1;
ctx.save();
groupsComputedThisFrame = false;
// I donβt want to trigger multiple tools at once,
// so Iβm temporarily changing the selected tool for transient tool shortcuts.
// This way I donβt have to worry about the if-else chain much.
// TODO: should I also show the temporary tool in the toolbox?
const prevTool = selectedTool;
// Quickly switch to the Precise Connector tool and back when you release β/β
// Other ways this could work (alternate UI ideas):
// - Add a point at the mouse connected to the closest point.
// - Connect the two points closest to the mouse.
if (keys.Slash) {
selectedTool = TOOL_PRECISE_CONNECTOR;
}
// handled differently (Space immediately triggers the Glue toolβs behavior)
// not sure it SHOULD though? could try it the other way
// if (keys.Space) {
// selectedTool = TOOL_GLUE;
// }
if (selectedTool === TOOL_SELECT && mouse.left && mousePrevious.left) {
selection = {
x: selection.x, y: selection.y,
x1: Math.min(selection.x, mouse.x),
y1: Math.min(selection.y, mouse.y),
x2: Math.max(selection.x, mouse.x),
y2: Math.max(selection.y, mouse.y),
points: [], connections: [],
};
for (var j = connections.length - 1; j >= 0; j--) {
var c = connections[j];
if (
c.p1.x < selection.x2 && c.p1.x > selection.x1 &&
c.p1.y < selection.y2 && c.p1.y > selection.y1 &&
c.p2.x < selection.x2 && c.p2.x > selection.x1 &&
c.p2.y < selection.y2 && c.p2.y > selection.y1
) {
selection.connections.push(c);
}
}
for (var i = points.length - 1; i >= 0; i--) {
var p = points[i];
if (
p.x < selection.x2 && p.x > selection.x1 &&
p.y < selection.y2 && p.y > selection.y1
) {
selection.points.push(p);
}
}
// draw selection rectangle
ctx.fillStyle = `rgba(0,255,200,${ghostTrails ? 0.01 : 0.1})`;
ctx.strokeStyle = "rgba(0,255,200,0.5)";
ctx.beginPath();
ctx.rect(
selection.x1 + .5,
selection.y1 + .5,
selection.x2 - selection.x1,
selection.y2 - selection.y1
);
ctx.fill();
ctx.stroke();
}
if (selectedTool === TOOL_SELECT) {
if (mouse.left && !mousePrevious.left) {
selection = { x: mouse.x, y: mouse.y, points: [], connections: [] };
}
} else if (selectedTool === TOOL_ADD_POINTS || selectedTool === TOOL_ADD_POINTS_QUICKLY) {
if (mouse.left && (!mousePrevious.left || selectedTool === TOOL_ADD_POINTS_QUICKLY)) {
if (!mousePrevious.left) undoable();
add_point_at_mouse();
}
} else if (selectedTool === TOOL_ADD_BALL) {
for (const ballToolState of ballToolStates) {
const { startPos, pointerPos } = ballToolState;
if (ballToolState.ball) {
// remove old ballβs points and connections
deletePoints(ballToolState.ball.points);
}
const variableDistances = keys.Shift;
ballToolState.ball = add_ball({
// x: mouse.x,
// y: mouse.y,
// numPoints: 5 + ~~(Math.random() * 4),
// size: 20 + Math.random() * 130,
// variableDistances: Math.random() > 0.5,
x: startPos.x,
y: startPos.y,
numPoints: ~~(Math.min(variableDistances ? 20 : 13, Math.max(3, (pointerPos.x - startPos.x) / 100 + 8))),
size: ~~(Math.abs(pointerPos.y - startPos.y) / 2 + 20),
variableDistances,
});
}
} else if (selectedTool === TOOL_ADD_DOLL) {
if (mouse.left && !mousePrevious.left) {
undoable();
add_doll({ x: mouse.x, y: mouse.y });
}
} else if (selectedTool === TOOL_ADD_ROPE) {
if (mouse.left) {
if (!mousePrevious.left) {
undoable();
}
const distBetweenPoints = 20;
let distToLast = lastRopePoint ? Math.hypot(mouse.x - lastRopePoint.x, mouse.y - lastRopePoint.y) : Infinity;
while (distToLast > distBetweenPoints) {
const newX = lastRopePoint ? lastRopePoint.x + (mouse.x - lastRopePoint.x) / distToLast * distBetweenPoints : mouse.x;
const newY = lastRopePoint ? lastRopePoint.y + (mouse.y - lastRopePoint.y) / distToLast * distBetweenPoints : mouse.y;
const newRopePoint = make_point({
x: newX,
y: newY,
fixed: keys.Shift,
color: keys.Shift ? "grey" : "#ce9e6b" //`hsl(${Math.random() * 50},${Math.random() * 50 + 15}%,${Math.random() * 50 + 50}%)`,
});
points.push(newRopePoint);
if (lastRopePoint) {
connections.push({
p1: lastRopePoint,
p2: newRopePoint,
dist: distBetweenPoints,
force: 1,
});
}
lastRopePoint = newRopePoint;
distToLast = lastRopePoint ? Math.hypot(mouse.x - lastRopePoint.x, mouse.y - lastRopePoint.y) : Infinity;
}
} else {
lastRopePoint = null;
}
} else if (selectedTool === TOOL_PRECISE_CONNECTOR) {
// I feel like angular similarity should also factor into this,
// maybe use polar coordinates and weigh the angle vs distance?
const closestPoint = findClosestPoint(mouse.x, mouse.y, preciseConnectorMaxDistToSelect);
const distBetweenPoints =
(connectorToolPoint && closestPoint) ?
Math.hypot(connectorToolPoint.x - closestPoint.x, connectorToolPoint.y - closestPoint.y) :
0;
// going with a standard distance for connections, unless itβs too long
// (at some point it would break), and in that case a custom distance
const standardDistance = 60;
const useCustomDistance = keys.Shift || distBetweenPoints > standardDistance * 2;
const existingConnection = connections.find(c =>
(c.p1 === connectorToolPoint && c.p2 === closestPoint) ||
(c.p2 === connectorToolPoint && c.p1 === closestPoint)
);
const canSelect = closestPoint && closestPoint !== connectorToolPoint;
const canConnect = connectorToolPoint && canSelect && !existingConnection;
if (mouse.left && !mousePrevious.left) {
connectorToolPoint = closestPoint;
} else if (mousePrevious.left && !mouse.left) {
if (canConnect) {
undoable();
connections.push({
p1: connectorToolPoint,
p2: closestPoint,
dist: useCustomDistance ? distBetweenPoints : standardDistance,
force: 1,
});
} else if (existingConnection) {
undoable();
const index = connections.indexOf(existingConnection);
if (index > -1) {
connections.splice(index, 1);
}
}
connectorToolPoint = null;
}
if (canSelect || connectorToolPoint) {
toolDraw(ctx,
existingConnection ? "disconnect" :
useCustomDistance ? "connect-varying-length" : "connect",
!!connectorToolPoint,
canConnect || existingConnection,
connectorToolPoint,
canSelect ? closestPoint : mouse
);
}
} else if (selectedTool === TOOL_GLUE) {
// handled elsewhere, except for creating undoable state
if (mouse.left && !mousePrevious.left) {
undoable();
}
}
const nearToMouse = findClosestPoint(mouse.x, mouse.y, dragMaxDistToSelect);
if (mouse.right && !mousePrevious.right) { // using LMB with Drag tool is handled elsewhere
rmbDragState = startDrag(mouse, mouse.pointerId);
}
if (!mouse.right && rmbDragState) {
const index = dragStates.indexOf(rmbDragState);
if (index > -1) {
dragStates.splice(index, 1);
}
rmbDragState = null;
}
for (const { dragging, dragOffsets, pointerPos } of dragStates) {
if (dragging.length) {
for (let i = 0; i < dragging.length; i++) {
const p = dragging[i];
const target_x = pointerPos.x + dragOffsets[i].x;
const target_y = pointerPos.y + dragOffsets[i].y;
if (play && !p.fixed) {
p.fx += (target_x - p.x) * mouseDragForce;
p.fy += (target_y - p.y) * mouseDragForce;
p.vx *= mouseDragDampingFactor;
p.vy *= mouseDragDampingFactor;
// within a certain distance, lerp to the target
const dist = Math.hypot(target_x - p.x, target_y - p.y);
const factor = 1 - Math.min(1, dist / mouseDragLerpDistance);
p.x += (target_x - p.x) * factor;
p.y += (target_y - p.y) * factor;
} else {
p.x = target_x;
p.y = target_y;
}
}
}
}
if (selectedTool === TOOL_DRAG && dragStates.every(({ dragging }) => !dragging.length) && nearToMouse) {
toolDraw(ctx, "drag", false, false, nearToMouse);
} else {
for (const { dragging } of dragStates) {
for (const p of dragging) {
toolDraw(ctx, "drag", true, false, p);
}
}
}
if (selectedTool !== TOOL_ADD_ROPE) {
// not important
// just prevents a weird scenario where you can continue a rope after switching tools while making a rope
lastRopePoint = null;
// you could do a similar thing with the select tool, but whatever
// itβs not like something bad happens
}
if (play) {
var freq = 440; // or something
var amplitude = 0;
//for(var g=0;g<4;g++){
for (var j = connections.length - 1; j >= 0; j--) {
var c = connections[j];
var d = Math.hypot((c.p1.x + c.p1.vx) - (c.p2.x + c.p2.vx), (c.p1.y + c.p1.vy) - (c.p2.y + c.p2.vy));
var dd = (d - c.dist);
var dx = (c.p2.x + c.p2.vx - c.p1.x - c.p1.vx);
var dy = (c.p2.y + c.p2.vy - c.p1.y - c.p1.vy);
//d=Math.abs(d)+1;
d++;
var f = c.force / 10;
c.p1.fx += dx / d * dd * f;
c.p1.fy += dy / d * dd * f;
c.p2.fx -= dx / d * dd * f;
c.p2.fy -= dy / d * dd * f;
// special handling for ragdolls
// try to keep legsβ points vertically aligned
if ((c.p1.part === "foot" && c.p2.part === "knee") || (c.p2.part === "foot" && c.p1.part === "knee")) {
const foot = c.p1.part === "foot" ? c.p1 : c.p2;
const knee = c.p1.part === "foot" ? c.p2 : c.p1;
if (knee.y > foot.y) {
knee.fy -= 0.5;
foot.fy += 0.5;
} else {
foot.fx += (knee.x - foot.x) * 0.5;
knee.fx -= (knee.x - foot.x) * 0.5;
}
foot.fx += Math.sin(Date.now() / 400 + foot.side * Math.PI / 4) * 0.6;
}
if ((c.p1.part === "knee" && c.p2.part === "hip") || (c.p2.part === "knee" && c.p1.part === "hip")) {
const knee = c.p1.part === "knee" ? c.p1 : c.p2;
const hip = c.p1.part === "knee" ? c.p2 : c.p1;
if (hip.y > knee.y) {
hip.fy -= 0.5;
knee.fy += 0.5;
} else {
knee.fx += (hip.x - knee.x) * 0.05;
hip.fx -= (hip.x - knee.x) * 0.05;
}
}
// and body (chest/bottom)
if ((c.p1.part === "chest" && c.p2.part === "bottom") || (c.p2.part === "chest" && c.p1.part === "bottom")) {
const chest = c.p1.part === "chest" ? c.p1 : c.p2;
const bottom = c.p1.part === "chest" ? c.p2 : c.p1;
chest.fx += (bottom.x - chest.x) * 0.2;
bottom.fx -= (bottom.x - chest.x) * 0.2;
bottom.fx += Math.sin(Date.now() / 400 * 2) * 0.6;
}
// breaking distance was previously c.dist * 3; c.dist + 120 keeps it the same for the standard distance of 60 (60*3 = 180 = 60 + 120), while making the rope stronger
if (dd > c.dist + 120) {
connections.splice(j, 1);
// console.log(dd);
amplitude += Math.min(Math.abs(dd), 100) / 100;
freq = 0;
}
if (!c.p1.fixed && !c.p2.fixed) {
var vd = Math.hypot(c.p1.vx - c.p2.vx, c.p1.vy - c.p2.vy);
var fd = Math.hypot(c.p1.fx - c.p2.fx, c.p1.fy - c.p2.fy);
var v = Math.hypot(c.p1.vx, c.p1.vy) + Math.hypot(c.p2.vx, c.p2.vy);
vdd = vd - (c.vdp || 0);
// var angle = Math.atan2(c.p1.x, c.p1.y, c.p2.x, c.p2.y);
if (audioStyle == 0) {
var amp_add = vd / 1000;
}
// var amp_add = vd / 1000;
// var amp_add = vd ** 1.2 / 1000;
// var amp_add = vd / 1000;
if (audioStyle == 1 || audioStyle == 2) {
var amp_add = vdd / 1000;