-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1819 lines (1688 loc) · 66.5 KB
/
index.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 lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Constrained Particle System Simulator</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@600&display=swap" rel="stylesheet">
<style>
html {
color: #555;
font-family: Arial, Helvetica, sans-serif;
}
input {
font-family: 'Source Code Pro', monospace;
font-weight: 600;
}
.load-container {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
backdrop-filter: blur(3px);
background-color: rgba(0, 0, 0, 0.2);
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
}
.load-text {
padding: 1em;
background-color: white;
box-shadow: rgb(0 0 0 / 12%) 0 0 4px, rgb(0 0 0 / 24%) 0 0 8px;
border-radius: 0.4em;
}
.control-panel-container {
position: fixed;
left: 0;
top: 0;
bottom: 0;
background-color: #eee;
box-shadow: rgb(0 0 0 / 12%) 1px 0 2px, rgb(0 0 0 / 24%) 2px 0 3px;
border-radius: 1em;
margin-right: 1.6em;
width: 600px;
display: flex;
transition: transform 0.3s ease-in-out;
z-index: 5;
}
.control-panel {
flex: 1;
overflow-x: hidden;
display: flex;
flex-direction: column;
}
.control-panel-switch {
width: 1.6em;
vertical-align: middle;
line-height: 100vh;
border-top-right-radius: 1em;
border-bottom-right-radius: 1em;
cursor: pointer;
text-align: center;
border-left: dashed 1px #ccc;
}
.control-panel-scroll {
overflow-y: scroll;
overflow-x: hidden;
flex: 1;
padding: 0 1em 1em 1em;
}
.control-panel-switch:hover {
background-color: #f5f5f5;
}
.control-panel-switch:active {
background-color: #ddd;
}
.title-group-container {
display: flex;
justify-content: center;
margin: 2em 0 1em 0;
}
.title-group {
display: inline-block;
margin-left: auto;
margin-right: auto;
}
.title {
margin: 0;
font-size: 1.7em;
}
.subtitle-container {
display: flex;
justify-content: space-between;
}
.subtitle {
color: #777;
margin: 0;
font-size: 1em;
}
h3 {
margin: 0.8em 0 0.4em 0;
}
input[type="text"],
input[type="number"] {
width: 100%;
}
.input-group {
flex: 1;
display: flex;
margin: 0 0 0.4em 1em;
font-size: 1.2em;
}
.input-group>input {
flex: 1;
margin-left: 0.5em;
padding: 0.2em;
outline: none;
}
.indent {
margin-left: 1em;
}
.input-h-group {
display: flex;
margin-bottom: -0.4em;
}
.integrator {
background-color: #ddd;
margin: 0.5em 0;
padding: 0.6em;
border-radius: 0.6em;
}
.integrator-title {
display: flex;
}
.integrator-title>h3 {
margin: 0 0 0 0.3em;
}
.graph-svg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
outline: none;
}
p {
text-align: justify;
margin: 0.4em 0 0 0;
}
button {
margin-top: 1em;
}
.error {
font-size: 0.8em;
font-weight: 600;
display: none;
white-space: pre-wrap;
font-family: 'Source Code Pro', monospace;
text-align: left;
word-break: break-all;
position: fixed;
right: 1em;
bottom: 1em;
z-index: 500;
color: white;
background-color: #b33;
padding: 1em;
border-radius: 1em;
}
.output {
font-size: 0.8em;
color: #777;
font-weight: 600;
white-space: pre-wrap;
font-family: 'Source Code Pro', monospace;
text-align: left;
word-break: break-all;
}
.fine-print {
font-size: 0.7em;
color: #777;
}
.color-indicator {
width: 0.8em;
height: 0.8em;
border-radius: 50%;
position: relative;
top: 0.2em;
margin-left: 0.2em;
}
.examples-container {
margin-top: -0.2em;
}
.examples-container button {
margin-top: 0.4em;
}
.examples-container li {
margin-left: -15px;
}
.editor-container {
margin-top: 0.5em;
height: 100px;
border-radius: 1em;
overflow: hidden;
}
.math-output {
overflow-x: auto;
background-color: #e5e5e5;
border-radius: 1em;
padding: 1em;
}
</style>
<!-- <script> -->
<script id="pyodide-worker" type="javascript/worker">
self.postMessage({ type: 'load', value: 'Downloading pyodide.js...' });
importScripts("https://cdn.jsdelivr.net/pyodide/v0.18.1/full/pyodide.js");
async function workerMain() {
self.postMessage({ type: 'load', value: 'Loading Python runtime...' });
const pyodide = await loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.18.1/full/",
});
self.postMessage({ type: 'load', value: 'Loading sympy...' });
await pyodide.loadPackage('sympy');
self.postMessage({ type: 'load', value: 'Loading numpy...' });
await pyodide.loadPackage('numpy');
self.postMessage({ type: 'load', value: 'Initializing Python environment...' });
pyodide.runPython(`
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations
from sympy.utilities.lambdify import implemented_function
transformations = standard_transformations
import numpy
import numpy as np
class Particle:
def __init__(self, index, positions, velocities, mass, Q, Q_all):
self._index = index
self._positions = positions
self._velocities = velocities
self.mass = mass
self._Q = Q
self._Q_all = Q_all
@property
def x(self):
return self._positions[self._index * 2]
@property
def y(self):
return self._positions[self._index * 2 + 1]
@property
def vx(self):
return self._velocities[self._index * 2]
@property
def vy(self):
return self._velocities[self._index * 2 + 1]
def apply_force(self, x_force, y_force):
self._Q[self._index * 2][0] += x_force
self._Q[self._index * 2 + 1][0] += y_force
self._Q_all.append([self._index, x_force, y_force])
`)
self.postMessage({ type: 'load', value: 'Warming up Python environment...' });
if (pyodide.runPython(`
str(parse_expr("5 * x+6 * y", transformations=transformations))
`) !== '5*x + 6*y') {
throw new Error('Sympy sanity check failed.');
}
if (pyodide.runPython(`
str(np.array([[1,2]]) @ np.array([[3],[4]]))
`) !== '[[11]]') {
throw new Error('Numpy sanity check failed.');
}
self.postMessage({ type: 'loadEnd' });
self.addEventListener('message', event => {
const data = event.data;
switch (data.type) {
case 'evalPython':
try {
if (data.context !== undefined) {
for (const key of Object.keys(data.context)) {
self[key] = data.context[key];
}
}
const resultPython = pyodide.runPython(data.python);
const result = (resultPython === undefined)
? undefined
: (resultPython.toJs === undefined)
? resultPython
: resultPython.toJs({
dict_converter: Object.fromEntries,
});
// console.warn(result);
self.postMessage({ type: 'evalResult', result });
} catch (error) {
self.postMessage({ type: 'evalResult', error });
}
break;
}
});
}
workerMain().catch(error => self.postMessage({ type: 'error', error: error.message }));
</script>
</head>
<body>
<div id="load-container" class="load-container">
<div class="load-text" id="load-text">
Loading JavaScript...
</div>
</div>
<div id="control-panel-container" class="control-panel-container">
<div class="control-panel">
<div class="title-group-container">
<div class="title-group">
<h1 class="title">Constrained Particle System Simulator</h1>
<div class="subtitle-container">
<h2 class="subtitle">By Rin Tepis</h2>
<h2 class="subtitle"></h2>
</div>
</div>
</div>
<div class="control-panel-scroll">
<h3>Simulation Settings:</h3>
<div class="input-group">
<label for="time-step-input">Time step = </label>
<input name="time-step-input" id="time-step-input" type="text" value="0.01">
</div>
<p class="indent" style="font-size: 1.2em;" id="speed-label">Animation speed = 1.00x</p>
<div class="input-h-group">
<div class="input-group">
<input style="margin: 0 10px 0 0" name="speed-input" id="speed-input" type="range" min="0" max="10"
value="1" step="0.01">
<button id="pause-button" style="margin: 0; width: 51px;">Pause</button>
<button id="reset-speed-button" style="margin: 0 0 0 0.8em; width: 51px;">Reset</button>
</div>
</div>
<p class="indent" style="font-size: 1.2em;" id="frame-label">Frame = </p>
<div class="input-h-group">
<div class="input-group">
<input style="margin: 0 10px 0 0" name="frame-input" id="frame-input" type="range" min="0" max="10"
value="1" step="0.01">
</div>
</div>
<p class="indent" style="font-size: 1.2em; margin-bottom: 0.2em;">Integrator:</p>
<div class="indent">
<input type="radio" id="integrator-1" name="integrator" value="1">
<label for="integrator-1" style="margin-right: 1em">Explicit Euler</label>
<input type="radio" id="integrator-2" name="integrator" value="2">
<label for="integrator-2" style="margin-right: 1em">Midpoint Method</label>
<input type="radio" id="integrator-3" name="integrator" value="3" checked>
<label for="integrator-3">RK4</label>
</div>
<h3>Feedback Terms:</h3>
<div class="input-h-group">
<div class="input-group">
<label for="ks-input">ks = </label>
<input name="ks-input" id="ks-input" type="number" value="1">
</div>
<div class="input-group">
<label for="kd-input">kd = </label>
<input name="kd-input" id="kd-input" type="number" value="1">
</div>
</div>
<h3>Constraint System:</h3>
<p>Please define the particles, constraints, and rendering options in the code editor below using Constrained
Particle System Simulator Language (CPSSL), a simple domain specific language I created for this project:</p>
<div id="system-editor-container" class="editor-container"></div>
<h3>Forces:</h3>
<p>Please define forces in the code editor below using Python:</p>
<div id="forces-editor-container" class="editor-container"></div>
<h3>Visibilities:</h3>
<input id="show-axises" name="show-axises" type="checkbox">
<label for="show-axises">Show axises</label>
<br />
<input id="show-crosshair" name="show-crosshair" type="checkbox">
<label for="show-crosshair">Show crosshair</label>
<br />
<input id="show-points" name="show-points" type="checkbox" checked="checked">
<label for="show-points">Show points</label>
<br />
<input id="show-vectors" name="show-vectors" type="checkbox" checked="checked">
<label for="show-vectors">Show force vectors</label>
<br />
<input id="show-dynamic-draws" name="show-dynamic-draws" type="checkbox" checked="checked">
<label for="show-dynamic-draws">Show dynamic draws</label>
<br />
<input id="show-static-draws" name="show-static-draws" type="checkbox" checked="checked">
<label for="show-static-draws">Show static draws</label>
<h3>Simulator Status:</h3>
<p id="main-status"></p>
<p id="error-output" class="error"></p>
<p>Particle positions:</p>
<p class="output" id="particle-positions"></p>
<p>Constraint error values:</p>
<p class="output" id="constraint-error-values"></p>
<p>Intermediary expressions:</p>
<p class="math-output" id="math-output"></p>
<h3>Examples:</h3>
<ul class="examples-container" id="examples-container"></ul>
<h3>Web Worker Status:</h3>
<p id="web-worker-evaluating">Currently running: False</p>
<p id="web-worker-queue-status">Tasks in queue: 0</p>
<p class="fine-print">This program uses a <a target="_blank"
href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Worker</a> (essentially a
separate thread) to run a <a target="_blank" href="https://pyodide.org/en/stable/">fully emulated Python
environment</a>, as JavaScript ecosystem lacks libraries that are suitable for scientific computations.
Unfortunately, due to <a target="_blank"
href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements">technical
limitations</a>, I cannot terminate a python computation from the main thread without restarting the entire
Web Worker. Therefore, if the Python environment is stuck (for example, when evaluating an impossible
integral, and for some reason sympy cannot tell that it is incapable of solving it), you have to manually
press the "Restart Web Worker" button below.</p>
<button id="restart-web-worker-button">Restart Web Worker</button>
</div>
</div>
<div id="control-panel-switch" class="control-panel-switch">◀</div>
</div>
<svg id="svg" class="graph-svg" xmlns="http://www.w3.org/2000/svg">
<style>
.hidden {
display: none;
}
.hide-trail .trail {
display: none;
}
.hide-points .point {
display: none;
}
.hide-vectors .vectors {
display: none;
}
.hide-axises .axises {
display: none;
}
.hide-dynamic-draws .svg-draws-container {
display: none;
}
.hide-static-draws .svg-static-draws-container {
display: none;
}
</style>
<g id="graph-panzoom-root" class="hide-axises" transform="matrix(207 0 0 207 1160 460)">
<path class="axises" id="axises" stroke="rgb(200, 200, 200)"></path>
<g class="svg-draws-container" id="svg-draws-container"></g>
<g class="svg-static-draws-container" id="svg-static-draws-container"></g>
<path class="vectors" id="vectors" fill="none" stroke="blue"></path>
<g id="points-container"></g>
</g>
<path id="crosshair-path" class="hidden" stroke="black"></path>
<text id="crosshair-x" class="hidden">x: 0</text>
<text id="crosshair-y" class="hidden">y: 0</text>
</svg>
<script src='https://unpkg.com/[email protected]/dist/panzoom.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.29.1/min/vs/loader.min.js"
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript" id="MathJax-script"
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
const $vectors = document.getElementById('vectors');
const $mathOutput = document.getElementById('math-output');
const $svg = document.getElementById('svg');
const $pointsContainer = document.getElementById('points-container');
const $svgDrawsContainer = document.getElementById('svg-draws-container');
const $svgStaticDrawsContainer = document.getElementById('svg-static-draws-container');
const $webWorkerEvaluating = document.getElementById('web-worker-evaluating');
const $webWorkerQueueStatus = document.getElementById('web-worker-queue-status');
/** New SVG node */
function nsn(tagName, attributes) {
var node = document.createElementNS('http://www.w3.org/2000/svg', tagName);
for (const [key, value] of Object.entries(attributes)) {
node.setAttribute(key, value);
}
return node;
}
function isSafeNumber(n) {
return Math.abs(n) < 1e6;
}
function clampNumber(n) {
return n;
}
function dedent(input) {
let commonIndent = 10000;
const split = input.split('\n');
for (const line of split) {
const match = line.match(/^[ \t]*(?=\S)/gm);
if (match === null) {
continue;
}
commonIndent = Math.min(commonIndent, match[0].length);
}
const result = [];
for (const line of split) {
result.push(line.substr(commonIndent));
}
return result.join('\n');
}
const $panzoomRoot = document.getElementById('graph-panzoom-root');
const pz = panzoom($panzoomRoot, {
maxZoom: 10000,
minZoom: 0.01,
});
const $controlPanelSwitch = document.getElementById('control-panel-switch');
const $controlPanelContainer = document.getElementById('control-panel-container');
let cpOpen = true;
$controlPanelSwitch.addEventListener('click', () => {
if (cpOpen) {
$controlPanelContainer.style.transform = 'translateX(calc(-600px + 1.6em))';
$controlPanelSwitch.innerText = '▶';
cpOpen = false;
} else {
$controlPanelContainer.style.transform = 'translateX(0)';
$controlPanelSwitch.innerText = '◀';
cpOpen = true;
}
});
const $loadText = document.getElementById('load-text');
const $loadContainer = document.getElementById('load-container');
async function main() {
const pyodideBlob = new Blob([document.getElementById('pyodide-worker').textContent], { type: "text/javascript" });
let pyodideWorker = new Worker(window.URL.createObjectURL(pyodideBlob));
const evalQueue = [];
let currentTask = null;
let evaluating = false;
function updateQueueStatus() {
$webWorkerEvaluating.innerText = `Currently running: ${evaluating ? 'True' : 'False'}`;
$webWorkerQueueStatus.innerText = `Tasks in queue: ${evalQueue.length + (+evaluating)}`;
}
function startQueue() {
if (evaluating) {
return;
}
if (evalQueue.length === 0) {
return;
}
evaluating = true;
currentTask = evalQueue.shift();
updateQueueStatus();
const { python, context, onStart } = currentTask;
if (onStart !== undefined) {
onStart();
}
pyodideWorker.postMessage({ type: 'evalPython', python, context });
}
function evalPython(python, context, onStart) {
let resolve;
let reject;
const promise = new Promise((r1, r2) => { resolve = r1; reject = r2; });
const task = {
python,
context,
onStart,
resolve,
reject,
};
evalQueue.push(task);
updateQueueStatus();
promise.cancel = () => {
const index = evalQueue.indexOf(task);
if (index !== -1) {
evalQueue.splice(index, 1);
updateQueueStatus();
}
};
startQueue();
return promise;
}
function loadWebWorker() {
return new Promise(resolve => {
pyodideWorker.addEventListener('message', event => {
const msg = event.data;
switch (msg.type) {
case 'load':
$loadText.innerText = msg.value;
break;
case 'loadEnd':
$loadContainer.style.display = 'none';
resolve();
break;
case 'error':
$loadText.innerText = msg.error;
break;
case 'evalResult':
if (msg.error !== undefined) {
currentTask.reject(new Error(msg.error));
} else {
currentTask.resolve(msg.result);
}
evaluating = false;
updateQueueStatus();
startQueue();
break;
}
});
});
}
$loadText.innerText = 'Loading Monaco editor...'
await loadWebWorker();
// $loadContainer.style.display = 'none';
const $examplesContainer = document.getElementById('examples-container');
const examples = [
{
name: 'Introduction with Tinkertoy (default)',
cpssl: dedent(`\
# To demonstrate the basics of Let's recreate the
# two-particle system in the assignment.
# First, we need to define two particles:
particle x1, y1 at 0.6, 0.8
particle x2, y2 at 0.6, 0.3
# Next, we need to define the two constraints:
constraint x1^2 + y1^2 = 1^2
constraint (x2 - x1)^2 + (y2 - y1)^2 = 0.5^2
# Finally, we need to declare what to draw (in addition
# to the particles):
draw circle(0, 0, 1)
draw segment(x1, y1, x2, y2)
# A more in-depth "tutorial" of CPSSL can be found in
# the Examples section below, with name "More CPSSL".`),
forces: dedent(`\
# You can write python here.
def accumulate_forces(particles):
# \`particles\` is an array of particles
for particle in particles:
# You can apply a force to a particle using the
# \`apply_force\` method
particle.apply_force(0, -9.8 * particle.mass)
# You can access a particle's position, velocities,
# and masses using \`particle.x\`, \`particle.y\`,
# \`particle.vx\`, \`particle.vy\`, and \`particle.mass\``),
}, {
name: 'More CPSSL',
cpssl: dedent(`\
# Here are some of the more "advanced" features of this
# simulator (and CPSSL):
# Particles can have mass (defaults to 1). You can define
# mass like so:
particle x1, y1 at 0.6, 0.8 with mass = 1.5
particle x2, y2 at 0.6, 0.3 with mass = 2
# You can define "auto" constraints. "Auto" constraints
# are constraints without eqaulity. This simulator will
# evaluate the value of the constraint with initial
# conditions, and use it as the rhs.
#
# You can define auto constraints like so:
constraint auto x1^2 + y1^2
constraint auto (x2 - x1)^2 + (y2 - y1)^2
draw segment(x1, y1, x2, y2)
# You can define a draw command to be "static". If
# static, it will only be rendered once at the beginning,
# which is perfect for that static circle.
draw static circle(0, 0, 1)
# You can also draw lines
draw line(0, 0, x1, y1)
# ...and functions with respect to x. The four parameters
# are: funcx(function, x0, x1, n_samples).
draw static funcx(sin(x) + 2, -10, 10, 200)
# Similarly, funcy also exists.
draw static funcy(exp(y - 3) + 2, -10, 10, 200)`),
forces: dedent(`\
# This demonstrates more than one forces
def accumulate_forces(particles):
for particle in particles:
particle.apply_force(0, -9.8 * particle.mass)
particle.apply_force(-particle.vx, -particle.vy)`),
}, {
name: 'Long chain',
cpssl: dedent(`\
# Let's build a long chain!
particle x1, y1 at 0.5, 0
particle x2, y2 at 1.0, 0
particle x3, y3 at 1.5, 0
particle x4, y4 at 2.0, 0
particle x5, y5 at 2.5, 0
particle x6, y6 at 3.0, 0
constraint auto x1^2 + y1^2
constraint auto (x2 - x1)^2 + (y2 - y1)^2
constraint auto (x3 - x2)^2 + (y3 - y2)^2
constraint auto (x4 - x3)^2 + (y4 - y3)^2
constraint auto (x5 - x4)^2 + (y5 - y4)^2
constraint auto (x6 - x5)^2 + (y6 - y5)^2
draw segment(0, 0, x1, y1)
draw segment(x1, y1, x2, y2)
draw segment(x2, y2, x3, y3)
draw segment(x3, y3, x4, y4)
draw segment(x4, y4, x5, y5)
draw segment(x5, y5, x6, y6)
`),
forces: dedent(`\
def accumulate_forces(particles):
for particle in particles:
particle.apply_force(0, -9.8 * particle.mass)`),
}, {
name: 'Rigid body?',
cpssl: dedent(`\
particle x1, y1 at -2, 1
particle x2, y2 at 2, 1
particle x3, y3 at -2, -1
particle x4, y4 at 2, -1
constraint auto x1^2 + y1^2
constraint auto (x1 - x2)^2 + (y1 - y2)^2
constraint auto (x1 - x3)^2 + (y1 - y3)^2
constraint auto (x1 - x4)^2 + (y1 - y4)^2
constraint auto (x2 - x3)^2 + (y2 - y3)^2
constraint auto (x2 - x4)^2 + (y2 - y4)^2
# constraint auto (x3 - x4)^2 + (y3 - y4)^2
# Uncomment the above line will cause instability
# immediately.
draw segment(x1, y1, x2, y2)
draw segment(x1, y1, x3, y3)
draw segment(x1, y1, x4, y4)
draw segment(x2, y2, x3, y3)
draw segment(x2, y2, x4, y4)
draw segment(x3, y3, x4, y4)
draw static circle(0, 0, sqrt(5))`),
forces: dedent(`\
def accumulate_forces(particles):
for particle in particles:
particle.apply_force(0, -9.8 * particle.mass)`),
}, {
name: 'Riding on sine wave',
cpssl: dedent(`\
particle x1, y1 at 0, 0
particle x2, y2 at 0, 1
constraint y1 = sin(x1)
constraint auto (x2 - x1)^2 + (y2 - y1)^2
draw segment(x1, y1, x2, y2)
draw static funcx(sin(x), -10, 50, 400)`),
forces: dedent(`\
def accumulate_forces(particles):
for particle in particles:
particle.apply_force(0, -9.8 * particle.mass)
particles[0].apply_force(12, 0)`),
}, {
name: 'Smile face',
cpssl: dedent(`\
# This is just to demonstrate that you can draw stuff
particle x1, y1 at 0.6, 0.8
particle x2, y2 at 0.6, 0.3
constraint auto x1^2 + y1^2
constraint auto (x2 - x1)^2 + (y2 - y1)^2
draw static circle(0, 0, 1)
draw static circle(-0.4, 0.3 ,0.2)
draw static circle(0.4, 0.3 ,0.2)
draw static funcx(x^2 - 0.5, -0.4, 0.4, 10)
draw segment(x1, y1, x2, y2)`),
forces: dedent(`\
def accumulate_forces(particles):
for particle in particles:
particle.apply_force(0, -9.8 * particle.mass)`),
},
];
require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.29.1/min/vs' } });
await new Promise(resolve => {
require(['vs/editor/editor.main'], resolve);
});
monaco.languages.register({ id: 'cpssl' });
monaco.languages.setMonarchTokensProvider('cpssl', {
keywords: ['particle', 'constraint', 'draw', 'at', 'with', 'mass', 'static', 'auto'],
functions: ['circle', 'segment', 'line', 'funcx', 'funcy', 'sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'sinc', 'asin', 'acos', 'atan', 'acot', 'asec', 'acsc', 'atan2', 'exp', 'log', 'sqrt', 'root', 'cbrt'],
tokenizer: {
root: [
[/\/\/.*$/, 'comment'],
[/#.*$/, 'comment'],
[/\d+/, 'number.float'],
[/[=><!~?:&|+\-*\/\^%]+/, 'operator'],
[/[()]+/, 'parentheses'],
[/[a-z_$][\w$]*/, {
cases: {
'@keywords': 'keyword',
'@functions': 'function',
'@default': 'identifier',
}
}],
],
}
});
monaco.editor.defineTheme('vsExtended', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'keyword', fontStyle: 'bold' },
{ token: 'function', foreground: 'FFAB2A' },
{ token: 'parentheses', fontStyle: 'bold' },
{ token: 'operator', foreground: 'AAAAAA' },
]
});
const cpsslModel = monaco.editor.createModel('', 'cpssl');
const $systemEditorContainer = document.getElementById('system-editor-container');
const $forcesEditorContainer = document.getElementById('forces-editor-container');
const cpsslEditor = monaco.editor.create($systemEditorContainer, {
model: cpsslModel,
minimap: {
enabled: false,
},
theme: 'vsExtended',
wordWrap: 'on',
scrollBeyondLastLine: false,
scrollbar: {
alwaysConsumeMouseWheel: false,
},
});
const forcesModel = monaco.editor.createModel('', 'python');
const forcesEditor = monaco.editor.create(document.getElementById('forces-editor-container'), {
model: forcesModel,
minimap: {
enabled: false,
},
theme: 'vsExtended',
wordWrap: 'on',
scrollBeyondLastLine: false,
scrollbar: {
alwaysConsumeMouseWheel: false,
},
});
function loadExample(example) {
cpsslModel.setValue(example.cpssl);
forcesModel.setValue(example.forces);
}
for (const example of examples) {
const $btn = document.createElement('button');
$btn.innerText = example.name;
$btn.addEventListener('click', () => {
loadExample(example);
update();
});
const $li = document.createElement('li');
$li.appendChild($btn);
$examplesContainer.appendChild($li);
}
loadExample(examples[0]);
const $mainStatus = document.getElementById('main-status');
const $errorOutput = document.getElementById('error-output');
const particles = [];
const constraints = [];
const drawCommands = [];
const staticDrawCommands = [];
const cpsslErrors = [];
const $svgPoints = [];
const $svgDraws = [];
const $svgStaticDraws = [];
let forceFunction = '';
let speed = 1;
let timeStep = 0.01;
let ks = 1;
let kd = 1;
let currentFrameFloat = 0;
const frames = [];
let currentUpdateId = 0;
let currentInitializerPromise = null;
let shouldAnimate = false;
let integrator = 3;
let revertSpeed = null;
let batchPromise = null;
let batchUpdateId = null;
let lineWidth = 3 / 207;
const $paths = new Set();
const $axises = document.getElementById('axises');
$paths.add($axises);
const $frameInput = document.getElementById('frame-input');
const $frameLabel = document.getElementById('frame-label');
function framesUpdated() {
if (frames.length === 0) {
$frameInput.disabled = true;
} else {
$frameInput.disabled = false;
$frameInput.max = frames.length;
}
$frameInput.value = Math.floor(currentFrameFloat);
$frameLabel.innerText = `Frame = ${Math.floor(currentFrameFloat)} (${frames.length} buffered)`;
}
$frameInput.addEventListener('input', () => {
currentFrameFloat = $frameInput.value;
});
let oldSpeed = 1;
$frameInput.addEventListener('mouseenter', () => {
oldSpeed = speed;
speed = 0;
});
$frameInput.addEventListener('mouseleave', () => {
speed = oldSpeed;
});
framesUpdated();
function updateLineWidth() {
const scale = pz.getTransform().scale;
lineWidth = 3 / scale;
for (const $point of $svgPoints) {
$point.setAttribute('r', lineWidth * 2);
}
for (const $svgDraw of $svgDraws) {
$svgDraw.setAttribute('stroke-width', lineWidth);
}
for (const $svgDraw of $svgStaticDraws) {
$svgDraw.setAttribute('stroke-width', lineWidth);
}
for (const $path of $paths) {
$path.setAttribute('stroke-width', lineWidth);
}
$vectors.setAttribute('stroke-width', lineWidth);
}
updateLineWidth();
updateGrid();
pz.on('zoom', () => {
updateLineWidth();