-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
1807 lines (1610 loc) · 72.5 KB
/
app.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 is the main file of mecEdit. You can find this apps repository {@link https://github.com/jauhl/mecEdit @GitHub}.
* @name mecEdit
* @author Jan Uhlig
* @copyright Jan Uhlig 2018
* @license MIT
* @requires examples.js
* @requires templates.js
* @requires appevents.js
* @requires g2.editor.js
* @requires mixin.js
* @requires slider.js
* @requires mec2.js
* @requires g2.js
*/
'use strict';
/**
* Container for inputs.
* @const
* @type {HTMLElement}
*/
const tooltip = document.getElementById('info'),
/**
* Container for inputs.
* @const
* @type {HTMLElement}
*/
actcontainer = document.getElementById('actuators-container'),
/**
* Container for charts.
* @const
* @type {HTMLElement}
*/
chartcontainer = document.getElementById('sb-canvas-container'),
/**
* SVG path container for run button.
* @const
* @type {HTMLElement}
*/
runSymbol = document.getElementById('run-symbol'),
/**
* Statusbar container for statusbar.
* @const
* @type {HTMLElement}
*/
statusbar = document.getElementById('statbar'),
/**
* Statusbar Statusbar container for dragmode.
* @const
* @type {HTMLElement}
*/
sbMode = document.getElementById('sbMode'),
/**
* Statusbar container for coordinates.
* @const
* @type {HTMLElement}
*/
sbCoords = document.getElementById('sbCoords'),
/**
* Statusbar container for coordinate mode.
* @const
* @type {HTMLElement}
*/
sbCartesian = document.getElementById('sbCartesian'),
/**
* Statusbar container for mouseevent property btn.
* @const
* @type {HTMLElement}
*/
sbBtn = document.getElementById('sbBtn'),
/**
* Statusbar container for mouseevent property dbtn.
* @const
* @type {HTMLElement}
*/
sbDbtn = document.getElementById('sbDbtn'),
/**
* Statusbar container for frames per second.
* @const
* @type {HTMLElement}
*/
sbFPS = document.getElementById('sbFPS'),
/**
* Statusbar container for g2.editor state.
* @const
* @type {HTMLElement}
*/
sbState = document.getElementById('sbState'),
/**
* Statusbar container for g2.editor state `dragging`.
* @const
* @type {HTMLElement}
*/
sbDragging = document.getElementById('sbDragging'),
/**
* Statusbar container for `App.prototype.editing`.
* @const
* @type {HTMLElement}
*/
sbDragmode = document.getElementById('sbDragmode'),
/**
* Statusbar container for `model.dof`.
* @const
* @type {HTMLElement}
*/
sbDOF = document.getElementById('sbDOF'),
/**
* Statusbar container for `App.prototype.gravity`.
* @const
* @type {HTMLElement}
*/
sbGravity = document.getElementById('sbGravity'),
/**
* g2.editor instance.
* @const
* @type {object}
*/
editor = g2.editor(),
/**
* Pi.
* @const
* @type {number}
*/
pi = Math.PI,
/**
* SVG play symbol.
* @const
* @type {string}
*/
svgplay = 'M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z',
/**
* SVG pause symbol.
* @const
* @type {string}
*/
svgpause = 'M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z';
/**
* Returns a origin symbol as a g2-object.
* @method
* @returns {object}
*/
const origin = g2().beg({ lc: 'round', lj: 'round', ls:()=>app.show.darkmode?'silver':'slategray', fs: 'darkgray' })
.p()
.m({ x: 21, y: 0 })
.l({ x: 0, y: 0 })
.l({ x: 0, y: 21 })
.stroke()
.p()
.m({ x: 35, y: 0 })
.l({ x: 21, y: -2.6 })
.a({ dw: pi/3, x: 21, y: 2.6 })
.z()
.m({ x: 0, y: 35 })
.l({ x: 2.6, y: 21 })
.a({ dw: pi/3, x: -2.6, y: 21 })
.z()
.drw()
.cir({ x: 0, y: 0, r: 2.5, fs: '#ccc' })
.end()
.beg({ ls:()=>app.show.darkmode?'silver':'slategray', font: '14px roboto'})
.txt({str:'x', x: 38, y: 4})
.txt({str:'y', x: 6, y: 30})
.end();
// deprecated
// /**
// * Returns a gravity vector as a g2-object.
// * @method
// * @returns {object}
// */
// const gravvec = (cartesian = true) => {
// const ytxt = cartesian ? -20 : -15;
// return g2().beg({ w: -pi/2, lw: 2, ls:()=>app.show.darkmode?'silver':'slategray', fs: 'darkgray'})
// .p()
// .m({ x: 0, y: 0 })
// .l({ x: 50, y: 0 })
// .stroke()
// .p()
// .m({ x: 50, y: 0 })
// .l({ x: 50 - 17.5, y: -3.5 })
// .a({ dw: pi/3, x: 50 - 17.5, y: 3.5 })
// .z()
// .drw()
// .end()
// .beg({ ls:()=>app.show.darkmode?'silver':'slategray', font: '14px roboto'})
// .txt({str:'g', x: -15, y: ytxt})
// .end();
// };
/**
* Container for `create()` & `prototype()`.
* @typedef {object}
*/
const App = {
/**
* Instantiate the app from `App.prototype`.
* @method
* @returns {object} - Extended app object with mixins.
*/
create() {
const o = Object.create(this.prototype);
o.constructor.apply(o, arguments);
return o;
},
/**
* Prototype object to instantiate the app from.
* @const {object}
*/
prototype: Object.assign({
/**
* Sets properties to parent object. Call with `apply()` and pass the parent.
* @method
*/
constructor() {
/**
* The model.
* @const
* @type {object}
*/
this.model = {
"id":"linkage"
};
/**
* mecEdit version.
* @const
* @type {string}
*/
this.VERSION = '0.7.0';
/**
* mixin requirement.
* @const
* @type {boolean}
*/
this.evt = { dx: 0, dy: 0, dbtn: 0 };
this.view = { x: 150, y: 150, scl: 1, cartesian: true };
this.cnv = document.getElementById('canvas');
this.ctx = this.cnv.getContext('2d');
this.instruct = document.getElementById('instructions');
this.ctxmenu = document.getElementById('contextMenu');
this.ctxmenuheader = document.getElementById("contextMenuHeader");
this.ctxmenubody = document.getElementById("contextMenuBody");
this.mecDefaults = {
// nodeScaling: false,
// darkmode: false,
// nodeLabels: false,
// constraintLabels: true,
// loadLabels: true,
nodes: true,
constraints: true
};
// states
this.build = false; // build state
this.tempElm = false; // contextmenu/view state
this.charts = {}; // { canvasid:{ctx:... , g:,,, } , ... }
this.devmode = false;
this.importConfirmed = false; // skip confirmdialogue helper
this.dragMove = true;
this.alyValues = { // possible values for view-components
model: {
tracePoint: ['cog']
},
nodes: {
info: ['m','vel','acc','force','velAbs','accAbs','forceAbs','energy'],
vector: ['vel','acc','force'],
tracePoint: ['pos']
},
constraints: {
info: ['w','wt','wtt','r','rt','rtt','forceAbs','moment'],
vector: [], // ['polAcc','polChgVel'] currently not really working
tracePoint: ['pole','velPole','accPole','inflPole']
}
};
// deprecated
// this.nodeInfoValues = ['m','vel','acc','force','velAbs','accAbs','forceAbs','energy'];
// this.constraintInfoValues = ['w','wt','wtt','r','rt','rtt','forceAbs','moment'];
// this.nodeVectorValues = ['acc','vel','force']; // objects only
this.g = g2();
this.registerEventsFor(this.ctx.canvas)
.on(['pointer','buttondown', 'buttonup', 'click'], e => { this.g.exe( editor.on(this.pntToUsr(Object.assign({}, e))) ) }) // ... apply events to g2
.on(['pointer', 'drag', 'pan', 'fps', 'buttondown', 'buttonup', 'click', 'pointerenter', 'pointerleave'], () => this.showStatus())
.on('drag', e => {
// if (this.editing) { // dragEdit mode // now in in elm.drag()
// editor.curElm.x0 = editor.curElm.x;
// editor.curElm.y0 = editor.curElm.y;
// };
this.g.exe(editor.on(this.pntToUsr(Object.assign({}, e)))) // ... apply drag event to g2
// .exe(this.ctx); // ... and render
this.showTooltip(e);
})
.on('pan', e => {
this.pan(e);
this.g.exe(this.ctx);
})
.on('pointer', e => this.showTooltip(e)) // show tooltip view info
.on(['buttonup', 'click'], () => this.hideTooltip()) // hide tooltip info
.on('buttondown', () => {
if (this.build) {
if (['addnode', 'addbasenode'].includes(this.build.mode)) this.addNode();
if (this.build.mode === 'purgeelement') this.purgeElement(editor.curElm);
if (['free', 'tran', 'rot'].includes(this.build.mode)) this.addConstraint();
if (this.build.mode === 'drive') this.addDrive(editor.curElm);
if (this.build.mode === 'force') this.addForce();
if (this.build.mode === 'spring') this.addSpring();
if (['fix', 'flt'].includes(this.build.mode)) this.addSupportShape();
}
})
.on('render', () => {
this.g.exe(this.ctx);
if (Object.keys(this.charts).length) { // this.model.state.hasChart also true for charts on main canvas...
for (const chart in this.charts) { // this.charts doesn't have iterator
this.charts[chart].g.exe(this.charts[chart].ctx);
}
}
})
.on('tick', e => this.tick(e));
this.state = 'created';
}, // constructor
/**
* Get this.dragMove state.
* @const
* @type {boolean}
*/
get editing() {
return !this.dragMove;
},
/**
* Set this.dragMove state.
* @const
* @type {boolean}
*/
set editing(q) {
this.dragMove = !q;
},
/**
* Evaluates used coordinate system.
* @const
* @type {boolean}
*/
get cartesian() { return this.view.cartesian; },
/**
* Height of the canvas.
* @const
* @type {number}
*/
get height() { return this.ctx.canvas.height; },
/**
* State of g2.editor. `true` if element is being dragged.
* @const
* @type {booelan}
*/
get dragging() { return !!(editor.curState & g2.DRAG) },
/**
* Updates the contents of the statusbar.
* @method
*/
showStatus() {
let { x, y } = this.pntToUsr({ x: this.evt.x, y: this.evt.y });
sbCoords.innerHTML = `x=${x}, y=${y}`;
sbDragmode.innerHTML = `dragmode=${this.editing?'edit':'move'}`;
sbDOF.innerHTML = `dof=${this.model.dof}`;
sbFPS.innerHTML = `fps=${this.fps}`;
// if (!!this.model.nodes && this.model.nodes.length > 0 ) { // only useful when model has nodes
// sbDOF.innerHTML = `dof=${this.model.dof}`;
// if (this.devmode)
// sbGravity.innerHTML = `gravity=${this.model.hasGravity ? 'on' : 'off'}`;
// } else {
// sbDOF.innerHTML = sbGravity.innerHTML = `dof`;
// };
if (this.devmode) {
sbGravity.innerHTML = `gravity=${this.model.hasGravity ? 'on' : 'off'}`;
sbMode.innerHTML = `mode=${this.evt.type}`;
sbCartesian.innerHTML = `cartesian=${this.cartesian}`;
sbBtn.innerHTML = `btn=${this.evt.btn}`;
sbDbtn.innerHTML = `dbtn=${this.evt.dbtn}`;
sbState.innerHTML = `state=${g2.editor.state[editor.curState]}`;
sbDragging.innerHTML = `dragging=${this.dragging}`;
};
},
/**
* Shows the tooltip.
* @method
*/
showTooltip(e) {
const info = this.model.info;
// type of info
if (editor.dragInfo && this.editing) {
tooltip.innerHTML = editor.dragInfo;
tooltip.style.display = 'inline';
} else if (info && !this.editing) { // don't show info-views when editing
tooltip.innerHTML = info;
tooltip.style.display = 'inline';
}
else
this.hideTooltip();
// update position only when visible
if (tooltip.style.display === 'inline') {
tooltip.style.left = ((e.clientX) + 15) + 'px';
tooltip.style.top = (e.clientY - 50) + 'px';
}
},
/**
* Hides the tooltip.
* @method
*/
hideTooltip() {
tooltip.style.display = 'none';
},
/**
* Reset the model, drive inputs and the app state.
* @method
* @param {object} e - Event or Object containing the timestep.
* @param {object} e.dt - Timestep.
*/
tick(e) {
if (!!this.model) { // check if model is defined first
if (this.dragging) {
this.editing ? this.updDependants(editor.curElm) : this.model.pose(); // null, if updating on dragend via editor
}
else if (this.state === 'active') { // perform time step
this.model.tick(1/60);
// if (!this.model.valid) this.idle();
if (!this.model.isActive)
this.stop(); // this causes state intentionally being set to 'idle' for model without gravity even when run was clicked
}
else if (this.state === 'input') { // perform time step, input state is only set from slider.js events!
this.model.tick(0);
}
// this.g.exe(this.ctx);
this.notify('render');
}
},
/**
* Initializes the app.
* @method
*/
init() { // evaluate how many drives and add init add controlled properties to model instead of typing them there
mec.model.extend(this.model,this);
this.model.init();
this.model.asmPos();
this.updateg();
while (actcontainer.lastChild) { // empty actcontainer if not empty already
actcontainer.removeChild(actcontainer.lastChild);
};
while (chartcontainer.lastChild) { // empty chartcontainer if not empty already
chartcontainer.removeChild(chartcontainer.lastChild);
};
this.charts = {}; // (re-)empty chart tracker
this.model.inputs = []; // track drives by id and dof for responsive range-input sizing
this.checkForPreviews(); // check if model has preview-views and set model state accordingly
this.checkForCharts(); // check if model has chart-views and set model state accordingly
let drv, prv=false;
while (drv = this.driveByInput(prv)) {
let id = drv.constraint.id+'-'+drv.value;
let max = (drv.value === 'ori') ? Math.round(drv.constraint.ori.Dw*180/pi) : Math.round(drv.constraint.len.Dr); // max value of range input (min always 0)
actcontainer.appendChild(this.createInputSlider(id, (this.cnv.width - 150)/2, max));
let elm = document.getElementById(id);
mecESlider.RegisterElm(elm);
elm.initEventHandling(this, id, this.model.constraintById(drv.constraint.id)[drv.value].inputCallbk);
this.model.inputs.push(id);
prv = drv;
};
if (typeof t === 'undefined' || t === null) // dont start second timer if init() is called again
this.startTimer(); // start synchronized ticks
this.toggleGravity(false, true);
// this.state = (this.model.inputs.length > 0) ? 'input' : 'initialized';
// visuals ...
// set color of sidebar-toggle-button to show if model has charts
document.querySelector('#sidebar-toggle').style.color = !!this.model.state.hasChart ? '#fff' : '#6c757d';
// expand or retract sidebar for charts
document.querySelector('#sb-r').style['padding-left'] = !!this.model.state.hasChart ? '0px' : '270px';
runSymbol.setAttribute('d',svgplay); // for reinits
Object.assign(this.show, { ...this.mecDefaults }); // reset to defaults (show nodes etc.)
this.state = 'initialized';
},
/**
* Sets the model to `active`.
* @method
*/
run() {
this.state = (this.model.inputs.length > 0) ? 'input' : 'active';
runSymbol.setAttribute('d',svgpause);
},
/**
* Pauses the model and resets the app state.
* @method
*/
idle() {
this.state = 'idle'; // when model has inputs and dof>0 it might still move
runSymbol.setAttribute('d',svgplay);
},
/**
* Stops the model and resets the app state.
* @method
*/
stop() {
this.model.stop();
this.idle();
},
/**
* Reset the model, drive inputs and the app state.
* @method
*/
reset() {
this.model.reset();
// reset drive-inputs
for (const drive in this.model.inputs) {
let ident = this.model.inputs[drive].split('-'); // eg.: ident = ['a','len']
this.model.constraintById(ident[0])[ident[1]].inputCallbk(0); // reset driven constraints
document.getElementById(ident[0]+'-'+ident[1]).value = 0;
this.notify(ident[0]+'-'+ident[1],0);
};
this.model.asmPos(); // necessary because model.reset() does not respect constraint r0 values
this.notify('render');
this.idle();
},
/**
* Reinitializes all dependants of the passed element.
* @method
* @param {object} elm - Element whose dependants should be reinitialized.
*/
// updDependants(elm) {
// let dependants = {ori:[],len:[]}; // declaring and filling array would be way more efficient in app scope since dependents don't change during drag
// // for (const el of this.model.constraints) {
// // if (el.dependsOn(elm) && ( (el.ori.type === 'const' && el.ori.ref)
// // || el.ori.type === 'drive'
// // || (el.len.type === 'const' && el.len.ref)
// // || el.len.type === 'drive')) {
// // // if (el.dependsOn(elm) && (el.ori.type === 'drive' || el.len.type === 'drive')) {
// // dependants.push(el);
// // }
// // };
// for (const el of this.model.constraints) {
// if (el.dependsOn(elm)) {
// if ( (el.ori.type === 'const' && el.ori.ref) || el.ori.type === 'drive' ) {
// dependants.ori.push(el);
// }
// if ( (el.len.type === 'const' && el.len.ref) || el.len.type === 'drive' ) {
// dependants.len.push(el);
// }
// }
// // if (el.dependsOn(elm) && (el.ori.type === 'drive' || el.len.type === 'drive')) {
// };
// console.log(dependants);
// // debugger
// // dependants.forEach(el => el.init(this.model)); // since only needed for drives, maybe implement user setting to choose between performance & simplicity
// // dependants.ori.forEach(el => {
// // if (el.ori.type === 'drive')
// // el.w0 = el.w
// // // el.init_ori_drive(el.ori)
// // if (el.len.type === 'drive')
// // el.init_len_drive(el.len)
// // // el.init(this.model);
// // });
// dependants.ori.forEach(el => el.w0 = el.w);
// dependants.len.forEach(el => el.r0 = el.r);
// if (this.model.state.hasChartPreview || this.model.state.hasTracePreview)
// this.model.preview();
// },
updDependants(elm) {
let dependants = []; // declaring and filling array would be way more efficient in app scope since dependents don't change during drag
for (const el of this.model.constraints) {
// if (el.dependsOn(elm) && ( (el.ori.type === 'const' && el.ori.ref)
// || el.ori.type === 'drive'
// || (el.len.type === 'const' && el.len.ref)
// || el.len.type === 'drive')) {
if (el.dependsOn(elm) && (el.ori.type === 'drive' || el.len.type === 'drive')) {
dependants.push(el);
}
};
// dependants.forEach(el => el.init(this.model)); // since only needed for drives, maybe implement user setting to choose between performance & simplicity
dependants.forEach(el => {
if (el.ori.type === 'drive')
el.w0 = el.w
// el.init_ori_drive(el.ori)
if (el.len.type === 'drive')
el.r0 = el.r
// el.init_len_drive(el.len)
// el.init(this.model);
});
if (this.model.state.hasChartPreview || this.model.state.hasTracePreview) {
this.model.preview();
} else { // mere eyecandy...
this.model.reset();
this.model.pose();
};
},
/**
* Toggle developer mode to show additional information in the statusbar.
* @method
*/
toggleDevmode() {
this.devmode = !this.devmode;
if (!this.devmode)
sbGravity.innerHTML = sbMode.innerHTML = sbCartesian.innerHTML = sbBtn.innerHTML = sbDbtn.innerHTML = sbState.innerHTML = sbDragging.innerHTML = ``;
this.showStatus();
},
/**
* Switch between dark- and lightmode.
* @method
* @param {boolean} eventTarget - true when invoked by gui event, e.g. 'click'
*/
toggleDarkmode(eventTarget = false) {
this.show.darkmode = !this.show.darkmode;
this.jsonEditor.setOption("theme",`${this.show.darkmode ? 'lucario' : 'mdn-like'}`);
this.cnv.style.backgroundColor = this.show.darkmode ? '#344c6b' : '#eee7';
// handle toggle switch in navbar when called programmatically or from element that isn't linked to the checkbox
if (!eventTarget) {
const toggle = document.querySelector('#darkmode');
if (this.show.darkmode && !toggle.checked) {
toggle.checked = true;
} else if (!this.show.darkmode && toggle.checked) {
toggle.checked = false;
}
}
this.notify('render');
},
/**
* Switch gravity in model on or off.
* @method
* @param {boolean} eventTarget - true when invoked by gui event, i.e. clicking
* @param {boolean} syncModel - set true to sync toggle state to model state, e.g. at init()
*/
toggleGravity(eventTarget = false, syncModel = false) {
if (!syncModel)
this.model.gravity.active = !this.model.gravity.active;
// handle toggle switch in navbar when called programmatically or from element that isn't linked to the checkbox
if (!eventTarget || syncModel) {
const toggle = document.querySelector('#gravity');
if (this.model.gravity.active && !toggle.checked) {
toggle.checked = true;
} else if (!this.model.gravity.active && toggle.checked) {
toggle.checked = false;
}
}
// app.updateg(); // to be removed
this.notify('render');
},
// /**
// *
// * @method
// */
// toggleHelper(flag = null, toogleId = null, invertFlag = false) {
// const flagVal = invertFlag ? !flag : flag;
// // handle toggle switch in navbar when called programmatically or from element that isn't linked to the checkbox
// if (toogleId) {
// const toggle = document.querySelector(`#${toogleId}`);
// if (flagVal && !toggle.checked ) {
// toggle.checked = true;
// } else if (!flagVal && toggle.checked) {
// toggle.checked = false;
// }
// }
// this.notify('render');
// },
/**
* Reset `this.view` to its initial state.
* @method
*/
resetView() {
this.view.x = 150;
this.view.y = 150;
this.view.scl = 1;
this.view.cartesian = true;
this.notify('render');
},
/**
* Create a new HTML-container for drive inputs.
* @method
* @param {string} actuated - Id of the new HTML-container (e.g. `a-ori`).
* @param {number} width - maximal width of the new HTML-container.
* @param {number} max - max value of the new HTML-range-input.
* @returns {HTMLElement} newC - Constraint replacing.
*/
createInputSlider(actuated, width, max) {
let template = document.createElement('template');
template.innerHTML = `<mecedit-slider id="${actuated}" class="mecedit-slider d-inline-flex nowrap ml-2 mr-1 mt-1" width="${width}" min="0" max="${max}" step="1" value="" valstr="${actuated}={value}${actuated.includes('ori')?'°':'u'}"></mecedit-slider>`
return template.content.firstChild;
},
/**
* Builds and updates the g2-command-queue according to the model.
* @method
*/
updateg() {
let apphasmodel = !!(typeof this.model === 'object' && Object.keys(this.model).length);
this.g = g2().clr()
.view(this.view)
.grid({ color: ()=>this.show.darkmode?'rgba(255, 255, 255, 0.1)':'rgba(0, 0, 0, 0.1)', size: 100 })
.grid({ color: ()=>this.show.darkmode?'rgba(255, 255, 255, 0.1)':'rgba(0, 0, 0, 0.1)', size: 20 })
.p() // mark origin
.m({ x: () => -this.view.x / this.view.scl, y: 0 })
.l({ x: () => (this.cnv.width - this.view.x) / this.view.scl, y: 0 })
.m({ x: 0, y: () => -this.view.y / this.view.scl })
.l({ x: 0, y: () => (this.cnv.height - this.view.y) / this.view.scl })
.z()
.stroke({ ls: ()=>this.show.darkmode?'rgba(255, 255, 255, 0.3)':'rgba(0, 0, 0, 0.2)', lw: 2 })
.use({grp:origin,x: () => (10 - this.view.x)/this.view.scl, y: () => (10 - this.view.y)/this.view.scl, scl: () => this.view.scl});
// if(apphasmodel && this.model.hasGravity) {
// if(this.cartesian) {
// this.g.use({grp:gravvec(true),x: () => (this.cnv.width - 30 - this.view.x)/this.view.scl, y: () => (this.cnv.height - 15 - this.view.y)/this.view.scl, scl: () => this.view.scl});
// } else {
// this.g.use({grp:gravvec(false),x: () => (this.cnv.width - 30 - this.view.x)/this.view.scl, y: () => (- this.view.y + 69 )/this.view.scl, scl: () => this.view.scl});
// };
// };
if (apphasmodel)
this.model.draw(this.g);
this.notify('render')
},
// /**
// * Create a canvas for a chart, set options & append to container.
// * @method
// * @param {object} chart - chart-view for canvas.
// */
// createCanvas(chart) {
// let canvas = document.createElement('canvas');
// canvas.id = chart.canvas;
// canvas.width = 350;
// canvas.height = 200;
// chartcontainer.appendChild(canvas);
// },
/**
* Builds a g2-command-queue for charts in secondary canvas-elements.
* @method
* @param {object} chart - chart-view for canvas.
*/
createChart(chart) {
// create canvas & set options
let canvas = document.createElement('canvas');
canvas.id = chart.canvas;
canvas.width = 350;
canvas.height = 200;
chartcontainer.appendChild(canvas);
// declare context as property
this.charts[chart.canvas] = {
ctx: document.querySelector(`#${chart.canvas}`).getContext('2d'),
g: g2().clr().view({cartesian: true})
};
// overwrite positioning
chart.x = chart.graph.x = chart.y = chart.graph.y = 40;
// declare g2-object and append chart-graphics
chart.draw(this.charts[chart.canvas].g);
// render
this.notify('render');
},
/**
* Resets the app and its stateful variables.
* @method
*/
resetApp() {
this.build = false; // reset build state
this.tempElm = false; // reset build state
this.instruct.innerHTML = ''; // reset instructions
this.notify('render');
},
// replaceNode(oldN, newN) { // deprecated
// if (!(oldN.x === newN.x)) this.model.nodeById(oldN.id).x = newN.x;
// if (!(oldN.y === newN.y)) this.model.nodeById(oldN.id).y = newN.y;
// if (!(oldN.m === newN.m)) this.model.nodeById(oldN.id).m = newN.m;
// },
/**
* Adds a new node to the model.
* @method
*/
addNode() {
if (editor.curElm === undefined || !editor.curElm.hasOwnProperty('m')) { // no node at coords; objects with a mass are considered nodes
let { x, y } = this.pntToUsr({ x: this.evt.x, y: this.evt.y });
let node = {
id: this.getNewChar(),
x: x,
y: y
};
if (this.build.mode === 'addbasenode')
node.base = true;
this.model.addNode(mec.node.extend(node)); // inherit prototype methods (extend) and add to model via model.addnode
node.init(this.model);
this.updateg(); // update graphics
} else { // existing node at coords
return;
};
if (!this.build.continue) {
document.body.style.cursor = 'default';
this.resetApp();
};
},
/**
* Removes all inputs of a constraint.
* @method
* @param {string} id - Id of the constraint the input belongs to.
*/
removeInput(id) {
for (let dof of ['-len','-ori']) {
if (this.model.inputs.includes(id+dof)) { // remove redundant ori inputs
actcontainer.removeChild(document.getElementById(id+dof));
this.model.inputs.splice(this.model.inputs.findIndex((el)=>el.id === id),1);
};
};
},
/**
* Removes the passed component and all its dependants.
* @method
* @param {object} elem - Element to be purged from the model.
*/
purgeElement(elem) { // identify and remove passed element and all its dependants
if (!!elem) { // check if an actual element was passed and not 'undefined'
if(['node','ctrl'].includes(elem.type)) {
let dependants = this.model.dependentsOf(elem).constraints;
if (dependants.length > 0) { // maybe dependants with inputs
for (let dep of dependants) {
if (this.model.inputs.includes(dep.id+'-ori') || this.model.inputs.includes(dep.id+'-len'))
this.removeInput(dep.id);
};
};
};
if (elem.type === 'node') {
this.model.purgeNode(elem);
} else if (['free','tran','rot','ctrl'].includes(elem.type)) {
if (this.model.inputs.includes(elem.id+'-ori') || this.model.inputs.includes(elem.id+'-len'))
this.removeInput(elem.id);
this.model.purgeConstraint(elem);
} else if (['force','spring'].includes(elem.type)) {
this.model.purgeLoad(elem);
// } else if (['vector','trace','info'].includes(elem.type)) { // views not detectable yet
// this.model.purgeView(elem);
} else { // propably misclicked
return;
};
this.updateg(); // update graphics
document.body.style.cursor = 'default';
this.resetApp();
};
},
/**
* Replaces an old Constraint with a new one.
* @method
* @param {object} oldC - Constraint to be replaced.
* @param {object} newC - Constraint replacing.
*/
replaceConstraint(oldC, newC) {
this.reset();
let rebindorilistener = false;
let rebindlenlistener = false;
let oridrv = false;
let lendrv = false;
if (newC.ori.type === 'drive')
oridrv = {newC, value:'ori'};
if (newC.len.type === 'drive')
lendrv = {newC, value:'len'};
// ori
if (!!oldC.ori && !!oldC.ori.input && !!document.getElementById(oldC.id+'-ori')) { // remove old eventlistener for updated drives
document.getElementById(oldC.id+'-ori').removeEventListener('input',this.model.constraintById(oldC.id).ori.inputCallbk,false);
if (!!newC.ori.input) // newC needs new eventlistener
rebindorilistener = true;
};
// len
if (!!oldC.len && !!oldC.len.input && !!document.getElementById(oldC.id+'-len')) { // remove old eventlistener for updated drives
document.getElementById(oldC.id+'-len').removeEventListener('input',this.model.constraintById(oldC.id).len.inputCallbk,false);
if (!!newC.len.input) // newC needs new eventlistener
rebindlenlistener = true;
};
this.model.constraints.splice(this.model.constraints.indexOf(this.model.constraintById(oldC.id)), 1); // remove old constraint
this.model.addConstraint(mec.constraint.extend(newC)); // add new constraint
newC.init(this.model); // init new constraint
this.updateg(); // update graphics
this.model.pose();
if ( (lendrv && !this.model.inputs.includes(newC.id+'-len')) || (oridrv && !this.model.inputs.includes(newC.id+'-ori')) ) { // drive has no input yet
let drv, prv=false;
while (drv = this.driveByInput(prv)) {
let id = drv.constraint.id+'-'+drv.value;
let max = (drv.value === 'ori') ? Math.round(drv.constraint.ori.Dw*180/pi) : Math.round(drv.constraint.len.Dr); // max value of range input (min always 0)
actcontainer.appendChild(this.createInputSlider(id, (this.cnv.width - 150)/2, max));
let elm = document.getElementById(id);
mecESlider.RegisterElm(elm);
elm.initEventHandling(this, id, this.model.constraintById(drv.constraint.id)[drv.value].inputCallbk);
this.model.inputs.push(id);
prv = drv;
};
window.dispatchEvent(new Event('resize')); // lazy range-width fitting ...
} else {
if (!newC.ori.input && this.model.inputs.includes(newC.id+'-ori')) { // remove redundant ori inputs
actcontainer.removeChild(document.getElementById(newC.id+'-ori'));
this.model.inputs = this.model.inputs.filter( el => el !== newC.id+'-ori' );
};
if (!newC.len.input && this.model.inputs.includes(newC.id+'-len')) { // remove redundant len inputs
actcontainer.removeChild(document.getElementById(newC.id+'-len'));
this.model.inputs = this.model.inputs.filter( el => el !== newC.id+'-len' );
};
};
// update range internals
if (!!oldC.ori && !!oldC.ori.input && !!oldC.ori.Dw && !!newC.ori && !!newC.ori.input && !!newC.ori.Dw && !(oldC.ori.Dw === newC.ori.Dw)) {
let mecslider = document.getElementById(newC.id+'-ori');
mecslider.max = mecslider.children[1].max = `${Math.round(newC.ori.Dw*180/Math.PI)}`;
};
if (!!oldC.len && !!oldC.len.input && !!oldC.len.Dr && !!newC.len && !!newC.len.input && !!newC.len.Dr && !(oldC.len.Dr === newC.len.Dr)) {
let mecslider = document.getElementById(newC.id+'-len');
mecslider.max = mecslider.children[1].max = `${Math.round(newC.len.Dr)}`;
};
if (rebindorilistener)
document.getElementById(oridrv.newC.id+'-ori').initEventHandling(this, oridrv.newC.id, this.model.constraintById(oridrv.newC.id)[oridrv.value].inputCallbk );
if (rebindlenlistener)
document.getElementById(lendrv.newC.id+'-len').initEventHandling(this, lendrv.newC.id, this.model.constraintById(lendrv.newC.id)[lendrv.value].inputCallbk );
this.state = 'initialized';
},
/**
* Searches for drives with inputs.
* @method
* @param {(object | boolean)} [prev = false] - Drive to start search from.
* @returns {(object | boolean)} Drive that was found or false if none was found.
*/
driveByInput(prev = false) { // from microapp.js
let found = false, start = !prev;
for (const constraint of this.model.constraints) {
if (constraint.ori && constraint.ori.type === 'drive' && constraint.ori.input) {
if (!start) start = constraint.ori === prev.constraint.ori;
else if (!this.model.inputs.includes(constraint.id+'-ori')) found = {constraint, value:'ori'};