-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlinear.js
More file actions
2709 lines (1974 loc) · 68.2 KB
/
linear.js
File metadata and controls
2709 lines (1974 loc) · 68.2 KB
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
var Linear={}; //holds the objects, for tidiness sake
//// GLOBAL CONSTRUCTORS ////
function system(A,B,C,D,X){
return new Linear.System(A,B,C,D,X);
}
function plot(sys,size,vars,limits,labels,colors){
return new Linear.Plot(sys,size,vars,limits,labels,colors);
}
function diagram(sys,size){
return new Linear.Diagram(sys,size);
}
function slider(vars,v,chf,title,limits){
return new Slider(vars,v,chf,title,limits);
}
function tBox(text){
return new TBox(text);
}
//// CLASSES ////
function Slider(vars,v,chf,title,limits){
var length=200;
var vert=false;
var container=document.createElement('div');
document.body.appendChild(container);
var titleSpan=document.createElement('span');
//titleSpan.style.fontFamily='monospace';
titleSpan.innerHTML=title;
container.appendChild(titleSpan);
var numBox=document.createElement('input');
try{numBox.type='number';}catch(e){}
numBox.style.width='4em';
numBox.value=0;
container.appendChild(numBox);
if(vert)container.appendChild(document.createElement('br'));
var oslide=document.createElement('div');
oslide.style.display='inline-block';
oslide.style.width=vert?'auto':length+'px';
oslide.style.height=vert?length+'px':'auto';
oslide.style.overflow='scroll'; //the X and Y overflows aren't supported by all
oslide.style.overflowX=vert?'hidden':'scroll';
oslide.style.overflowY=vert?'scroll':'hidden';
container.appendChild(oslide);
var islide=document.createElement('div');
islide.style.width =vert?'1px':length*10+'px';
islide.style.height=vert?length*10+'px':'1px';
oslide.appendChild(islide);
numBox.onchange=function(){
setVal(+numBox.value);
}
oslide.onscroll=vert?function(){
setVal(oslide.scrollTop/maxNum*range+limits[0]);
} : function(){
setVal(oslide.scrollLeft/maxNum*range+limits[0]);
}
function setVal(n){
var nval=n.toFixed(fix);
val=isNaN(nval)?val:nval; //if it's legal
if(numBox.val!=val) numBox.value=val;
var sval=Math.round((val-limits[0])/range*maxNum);
if(vert){
if(oslide.scrollTop!=sval) oslide.scrollTop=sval;
}else{
if(oslide.scrollLeft!=sval) oslide.scrollLeft=sval;
}
vars[v]=val;
if(chf)
chf();
}
//decide how many decimal points to use based on the upper limit.
var fix=Math.round(Math.log(limits[1])/Math.log(10))
fix=(fix<2?-fix+2:0);
var range=limits[1]-limits[0];
var val=0;
var maxNum=vert?oslide.scrollHeight-oslide.clientHeight:oslide.scrollWidth-oslide.clientWidth;
setVal(vars[v]);
}
function TBox(text){
var container=document.createElement('div');
container.style.padding='1px 0px';
var tSpan=document.createElement('span');
container.appendChild(tSpan);
this.place=function place(){
document.body.appendChild(container);
return this;
}
this.set=function set(text){
tSpan.innerHTML=text;
return this;
}
this.place();
this.set(text||''); //default to blank
}
//the system does the math; the simulation of the model
Linear.System=function System(nA,nB,nC,nD,nXi){
//system variables
var A=[];
var B=[];
var C=[];
var D=[];
var Xi=[];
var X=[];
var U=[];
var Y=[];
this.Y=Y; //make it public
//sim stuff
var t;
var fps=30; //frames per second
var h=0.01; //time per step;
var spf=15; //steps per frame
var tMax=0; //how long to run the simulation. 0=forever
var ssButton; //the start/stop button
var stepper; //the setInterval ID (if defined)
var pushers=[]; //things to notify every step
var updaters=[]; //things to notify every frame
var resetters=[]; //things to notify when we reset (plots)
var inputs=[]; //things to update (pass time to) every step (sub-step)
//make the start/stop button
var container=document.createElement('div');
document.body.appendChild(container);
container.className='container';
ssButton=document.createElement('input');
ssButton.type='button';
container.appendChild(ssButton);
//if parameters were provided
if(nA)
setP(nA,nB,nC,nD,nXi);
initial(); //set inital values for Y,
//doOutputs(); //update outputs.
//update(); //update updaters.
//public setters
this.tMax=function(v){tMax=v;return this;}
this.h =function(v){ h=v;return this;}
this.spf =function(v){ spf=v;return this;}
this.fps =function(v){ fps=v;return this;}
function initial(nXi,go){
for(var i in resetters)
resetters[i].reset();
if(nXi)
Xi=nXi;
stop();//make the start button
t=0;
doInputs(t); //get initial input values
if(!Xi.length){//if no initial conditions given, make them 0;
X=[];
for(var i in A) X[i]=0;
}else{
X=Xi.slice(0); //copy the array
}
doOutputs();
update();
if(go)
start();
}
//takes (A,B,C,D,[x]),
function setP(nA,nB,nC,nD,nXi){
A=nA;
B=nB;
C=nC;
D=nD;
if(nXi){
Xi=nXi;
}
//if X is length 0, the U,
if(!X.length){
if(B.length>0)for(var i in B[0]) U[i]=0; //U is the width of B's width
for(var i in C) Y[i]=0; //Y is the width of C's height
initial();
}
}
this.setP=setP;
this.initial=initial;
this.getT=function getT(){
return t;
}
function start(){
ssButton.value='stop';
ssButton.onclick=stop;
stepper=setInterval(step,1000/fps);
document.onkeydown=function(e){if(e.keyCode==32){stop();return false}}
}
function stop(){
ssButton.value='start';
ssButton.onclick=start;
stepper=clearInterval(stepper);
document.onkeydown=function(e){if(e.keyCode==32){start();return false;}}
}
function done(){
ssButton.value='reset';
ssButton.onclick=reset;
stepper=clearInterval(stepper);
document.onkeydown=function(e){if(e.keyCode==32){reset();return false;}}
}
function reset(){
// for(var i in resetters)
// resetters[i].reset();
initial();
}
function step(){
var i,j;
var K1=[], K2=[], K3=[], K4=[],
X1=[], X2=[], X3=[];
for(var s=0;s<spf;s++){
doInputs(t);
///STEP 1
for(i in X){ //i is row
K1[i]=0;
for(j in X){ //j is column
K1[i]+=A[i][j]*X[j];
}
}
///STEP 2
for(i in X){
X1[i]=X[i]+K1[i]*h/2;
}
for(i in X){ //i is row
K2[i]=0;
for(j in X){ //j is column
K2[i]+=A[i][j]*X1[j];
}
}
///STEP 3
for(i in X){
X2[i]=X[i]+K2[i]*h/2;
}
for(i in X){
K3[i]=0;
for(j in X){ //j is column
K3[i]+=A[i][j]*X2[j];
}
}
///STEP 4
for(i in X){
X3[i]=X[i]+K3[i]*h/2;
}
for(i in X){ //i is row
K4[i]=0;
for(j in X){ //j is column
K4[i]+=A[i][j]*X3[j];
}
}
//weighted average
for(i in X){
X[i]=X[i]+(K1[i]+2*K2[i]+2*K3[i]+K4[i])*h/6;
for(j in U){
X[i]+=B[i][j]*U[j]*h;
}
}
t+=h;
doOutputs()
}
update();
if(tMax && t>=tMax)
done();
}
function doOutputs(){
//update Y
for(var i in Y){
Y[i]=0;
for(var j in X){
Y[i]+=X[j]*C[i][j];
}
for(var j in U){
Y[i]+=U[j]*D[i][j];
}
}
for(var i in pushers)
pushers[i].push();
}
function update(){
for(var i in updaters)
updaters[i].update();
}
function doInputs(t){
for(var i in inputs){
inputs[i].update(t);
}
}
this.addUpdater=function addUpdater(thing){
updaters.push(thing);
}
this.addPusher=function addPusher(thing){
pushers.push(thing);
}
this.addResetter=function addResetter(thing){
resetters.push(thing);
}
//constructor for inputs
this.input=function input(v,func){
new InputFunc(v,func);
return this;
}
//an object
function InputFunc(v,func){
inputs.push(this);
this.update = function update(t){
U[v]=func(t);
}
}
}
//the plot plots the data from the System
Linear.Plot=function Plot(size,sys,vars,limits,labels,colors){
//sys is the linked System
//size is [w,h]
//limits is [xMin,xMax,yMin,yMax]
// or [xMax,yMin,yMax] (xMin=0)
// or [xMax,yMax] (xMin=0, yMin=-yMax)
//vars is an array of indicies of Y (numbers)
//labels is an array of names for the values being plotted
//updaters are called each frame,
//resetters are called on global reset,
//pushers are called every step (perhaps)?
var lineAttrs={'stroke-linejoin':'round','stroke-linecap':'round','stroke-width':'1'};
sys.addUpdater(this);
sys.addPusher(this);
sys.addResetter(this);
if(limits){
if(limits.length==2)
limits=[0,limits[0],-limits[1],limits[1]];
else if(limits.length==3)
limits=[0,limits[0],limits[1],limits[2]];
//if length==4, we don't need to do anything
}else{ //default
limits=[0,50,-20,20];
}
var Y;
var T;
var pts=[]; //pts holds plotted points. Points are in the form [x,y]. pts[n] is all the points of line n, and pts[n][m] is point m of line n.
//this.pts=pts;
this.getPts=function(){return pts}
// if vars is not specified, make it all the vars in Y
if(!vars){
vars=[];
for(i in sys.Y){
vars[i]=i;
}
}
var lPadding=20;
var vPadding=15;
//default colors
colors=colors?colors:
['#00A', //blue
'#A00', //red
'#0A0', //green
'#AA0', //yellow
'#A0A', //magenta
'#0AA'];//cyan
var container=document.createElement('div');
document.body.appendChild(container);
container.className='container';
var canv=Raphael(container,size[0],size[1]);
canv.canvas.className.baseVal='plot';
///for dumping data///
var isDump=false;
var precision=10;
var dumpBox=document.createElement('textArea');
dumpBox.className='plot';
dumpBox.style.width=size[0]+'px';
dumpBox.style.height=size[1]+'px';
dumpBox.style.display='inline-block';
dumpBox.style.overflow='auto';
dumpBox.style.fontFamily='monospace';
dumpBox.readOnly=true;
this.dumpBox=dumpBox;
var lastDrawn=[];
var errDist=.5; //allowable error - used by plotting algorithm
var chunkSize=50;
var chunkStart=[];
var oldLines=[];
this.oldLines=oldLines;
var lines=[]; //the Raphael Path objects
var paths=[]; //the path strings "M1,1L2,5..."
var scaleX=(size[0]-lPadding)/(limits[1]-limits[0]); // width/(xMax-xMin)
var scaleY=(size[1]-2*vPadding)/(limits[3]-limits[2]); // height/(yMax-yMin)
var offsX=-limits[0]*scaleX+.5+lPadding;
var offsY=-limits[3]*scaleY+.5-vPadding;
// var offsY=Math.floor(size[1]/2)+.5; //the floor and the +.5 make 0 lie on a pixel somehow
//that makes the axis 1 pixel wide instead of two
//the horizontal and vertical axis lines
var axis=canv.path(['M',0,-offsY,'h',size[0],
'M', offsX,0,'v',size[1]]);
axis.attr({'stroke-width':.5,'stroke':'#999'});
var aLabels=canv.set();
aLabels.push(canv.text(lPadding/2,vPadding,limits[3]));
aLabels.push(canv.text(lPadding/2,size[1]-vPadding,''+limits[2]));
aLabels.attr({fill:'#999'});
function newChunk(v){
if(lines[v]){
//lines[v].attr({'stroke-opacity':'.2'});
if(!oldLines[v])
oldLines[v]=[];
oldLines[v].push(lines[v]);
}
//for(var i in lines)lines[i].hide();
//create the lines
lines[v]=canv.path();
lines[v].attr(lineAttrs);
lines[v].attr({stroke:colors[v%colors.length]});
//lines[v].toBack();
if(labels){ //pull the legend in front of the new lines
legendBox.toFront();
legend.toFront();
}
chunkStart[v]=lastDrawn[v]?lastDrawn[v]:0;
}
//make the legend
if(labels){
//we need the rectangle to fit it's contents.
//we'll create the rectangle with size 1x1,
// then we make the legend lines and labels
// then we size the recatnage to fit the text using getBBox()
// and move it as to fulfill the margin parameter
var lMargin=10;
var lRad=2;
var sampleLength=30;
var lineHeight=14;
var legend=canv.set();
var legendBox=canv.rect(0,0,1,1,lRad);
var sample;
for(var v=0;v<vars.length;v++){
sample=canv.path(['M',13,v*lineHeight+12,'h',sampleLength]);
sample.attr ({stroke:colors[v%colors.length]});
legend.push(canv.text(sampleLength+22,v*lineHeight+12,labels[v]));
legend.push(sample);
}
legend.attr(lineAttrs);
legend.attr({'text-anchor':'start'});
//LEG=legend;
var legBox=legend.getBBox();
var lSize=[legBox.width+22,legBox.height+12];
legendBox.attr({width:lSize[0],height:lSize[1],'stroke-width':.5,stroke:'#AAA',fill:'#FFF','fill-opacity':.85});
legend.toFront(); //pull in front of the box
//legend.push(legendBox);
legendBox.translate(size[0]-lSize[0]-lMargin-2,lMargin);
legend. translate(size[0]-lSize[0]-lMargin-2,lMargin);
}
//push new values onto the Y vector
function pushVals(){
/// push the new data onto the Y and T vectors. ///
// this is only used by the data dump these days...
var vals=[];
for(var i=0;i<vars.length;i++){
vals.push(sys.Y[vars[i]]);
}
Y.push(vals);
T.push(sys.getT());
/// do the thing with the pts[] ///
if(pts.length!=vars.length){ //at the beginning
for(var v in vars){ //create the pts[v] vectors
pts[v]=[];
}
}
for(var i=0;i<vars.length;i++){
var pt=pts[i];
var ct=sys.getT(); //turns out getters are inefficient...
var cy=sys.Y[vars[i]];
if(pts[i].length<3){ //we'll blindly keep the first three points
pts[i].push([ct,cy]);
}else{ //for the rest, we do this crazy thing
//pt[n] : previous point
//pt[n-1]: point after the last anchor point (used to find slope)
//pt[n-2]: the last anchor point
var n=pt.length-1;
//we'll find the slope at the previous point
var slope=(pt[n-1][1]-pt[n-2][1])/(pt[n-1][0]-pt[n-2][0]);
//and project that line to the current time, and find the difference
var diff=cy-(pt[n-1][1]+(ct-pt[n-1][0])*slope);
//if the difference is unacceptable //, or if time hasn't changed (jk)
if(Math.abs(diff)>errDist/scaleY){ // || !(pt[n-1][0]-pt[n-2][0])){
//previous point becomes new anchor
//current point becomes new anchor+1
//current point also becomes previous point
pt[n-1]=pt[n];
pt[n]=[ct,cy];
pt.push([ct,cy]);
//for illustrating points
//canv.circle(pt[n-1][0]*scaleX+offsX,-(pt[n-1][1]*scaleY+offsY),1.5).attr({'fill':'none','stroke':colors[i%colors.length],'stroke-width':.3});
}else{ //otherwise just update the last index
pt[n]=[ct,cy];
}
}
}
}
function redraw(){
for(var v=0;v<vars.length;v++){
if(pts[v].length-chunkStart[v]>chunkSize || !paths[v]){
newChunk(v)
}
var n0=(chunkStart[v])-2*(chunkStart[v]>0)+1;
paths[v]='';
//paths[v]+='M'+(pts[v][0][0]*scaleX+offsX)+','+-(pts[v][0][1]*scaleY+offsY);
for(var n = n0; n<pts[v].length; n++){
if(n==n0)
paths[v]+='M'+(pts[v][n-1][0]*scaleX+offsX)+','+-(pts[v][n-1][1]*scaleY+offsY);
paths[v]+='L'+(pts[v][n][0]*scaleX+offsX)+','+-(pts[v][n][1]*scaleY+offsY);
}
lines[v].attr({path:paths[v]});
lastDrawn[v]=n-1;
}
}
//called every step
this.push=function push(){
pushVals();
//step();
}
//called every frame
this.update=function update(){ //called by the System
//pushVals();
step();
}
//happens every frame (and in the beginning)
function step(){
if(isDump){
//dump(); //problematic when we're getting ALL the data - maybe if we make it append instead of replace. maybe.
}else{
if(T[T.length-1]<=limits[1]+.1) //if we're within plot limits
redraw();
}
}
//clear the plot
this.reset=function reset(){
Y=[];
T=[];
pts=[];
lastDrawn=[];
for(var v in vars)
newChunk(v);
for(var i in oldLines){
for(var j in oldLines[i]){
oldLines[i][j].remove();
}
}
}
//make the double-click thing happen
container.ondblclick=function(e){ togDump(); }
function dump(){
//this is REALLY inefficient - if we made it more efficient (append) we might be able to do it realtime
var dumpText='';
for(var i in Y){
dumpText+=T[i].toPrecision(6).slice(0,6)+' ';
for(var j in Y[i]){
dumpText+=((Y[i][j]>=0)?' ':'')+Y[i][j].toPrecision(((Math.abs(Y[i][j])<1)?precision-1:precision))+' ';
}
dumpText+='\n';
}
//are we at the bottom?
var bottom= (dumpBox.scrollTop+dumpBox.clientHeight == dumpBox.scrollHeight);
//update text
dumpBox.innerHTML=dumpText;
//if we were at the bottom, scroll to the bottom.
if(bottom)
dumpBox.scrollTop = dumpBox.scrollHeight-dumpBox.clientHeight;
//dumpBox.select();
}
function togDump(){
if(isDump){ //undump
container.removeChild(dumpBox);
container.appendChild(canv.canvas);
redraw();
isDump=false;
}else{
container.removeChild(canv.canvas);
container.appendChild(dumpBox);
dump();
//dumpBox.select();
isDump=true;
}
}
this.reset();
pushVals();
step();
}
//The Diagram lets us draw various kinds diagrams, which can be animated using a System
Linear.Diagram=function Diagram(size,sys){
//diagrams now also have lScale, which scales linear values (masses and wheels)
// this is not for rotation, which might need it's own value
var lScale=1; //linear scale - default to 1.
var rScale=1; //rotation scale-default to 1.
this.lScale=function(scl){lScale=scl;return this;};
this.rScale=function(scl){rScale=scl;return this;};
var theDiagram=this;
var container=document.createElement('div'); //the div that will hold the vector canvas
document.body.appendChild(container); //append it to the document
container.className='container';
var canv=Raphael(container,size[0],size[1]);
canv.canvas.className.baseVal='diagram';
var bgColor='#FAFAFA'; //sometimes things erase areas by filling them with the bgColor.
var updaters=[]; //things to update every frame
//used for all text.
var textAttribs={'font-size':16,'font-style':'italic','font-family':'serif'}
//called by the system
this.update=function update(){
for(var i in updaters){
updaters[i].update();
}
}
var Y=sys?sys.Y:[]; //get the system's Y vector, or make an empty one
if(sys) sys.addUpdater(this);
/* ---- public "CONSTRUCTOR" functions ---- */
this.axis = function(origin,dir){ return new Axis(vect(origin[0],origin[1]),dir)}
this.mass = function(v,label,axis,rest,wheel,w,h,fname,fnameright){
return new Mass(v,label,axis,rest,wheel,w,h,fname,fnameright)}
this.spring=function(label,axis,mA,mB,off){return mkLink( 0,label,axis,mA,mB,off)}
this.dash = function(label,axis,mA,mB,off){return mkLink( 1,label,axis,mA,mB,off)}
this.rope = function(label,axis,mA,mB,off){return mkLink(-1,label,axis,mA,mB,off)}
this.wall = function(p,s,borders){return new HashBox(p,s,borders)}
//used by thermal systems to indicate insulation
this.block= function(p,s,label,color) {return new Block(p,s,label,color)}
//arrow() can be called in two ways:
//(v,A,rest,off,scale,name,namePos) or (v,[x,y],angle,scale,name,namePos)
this.arrow = function(v,a,b,c,d,e,f){
if(a.length) //a must be an [x,y] vector
return new Arrow(v,a,b,c,d,e);
else //a is probably an Axis
return new Arrow(v,[a.x(b)-Math.dsin(a.angle)*c,a.y(b)+Math.dcos(a.angle)*c],a.angle,d,e,f);
}
this.lArrow=function(p1,p2,label,dashed){return new LinArrow(p1,p2,label,dashed)}
//Element1 is for circuit elements on one point
this.node = function(p,label){return new Element1('N',p,label)}
this.ground = function(p,label){return new Element1('G',p,label)}
//Element2 is for elements between two points
this.wire = function(p1,p2,label){return new Element2( 'W',p1,p2,label)}
this.resistor = function(p1,p2,label){return new Element2( 'R',p1,p2,label)}
this.capacitor= function(p1,p2,label){return new Element2( 'C',p1,p2,label)}
this.inductor = function(p1,p2,label){return new Element2( 'L',p1,p2,label)}
this.source = function(p1,p2,label){return new Element2( 'S',p1,p2,label)}
this.sourceI = function(p1,p2,label){return new Element2('Si',p1,p2,label)}
this.sourceV = function(p1,p2,label){return new Element2('Sv',p1,p2,label)}
//terminals can have 1 or two terminals
this.terminal = function(a,b,c){
if(typeof b=='object' && typeof b[0]=='number'){
return new Element2( 'T',a,b,c);
}else{
return new Element1( 'T',a,b);
}
}
this.opAmp = function(p1,p2,label,w){return new OpAmp(p1,p2,label,w)}
this.meter=function(v,loc,range,label){return new Meter(v,loc,range,label)}
this.text=function(p,label){return new Text(p,label)}
this.line=function(p1,p2,w){return new Line(p1,p2,w)};
this.coil=function(p1,p2,w,r){return new Coil(p1,p2,w,r)}
this.axisR=function(origin,proj){return new AxisR(origin,proj)}
// this.cylinder=function(v,name,A,loc,w,r){return new Cylinder(v,name,A,loc,w,r)}
this.cylinder=function(v1,v2,name,A,loc,w,r,f,fname){return new Cylinder(v1,v2,name,A,loc,w,r,f,fname)}
this.pad=function(name,A,loc,w,r){return new Pad(name,A,loc,w,r)}
//aArrow can take different kinds of arguments:
//label,A,loc,r,ang,leng,lScale,w
//name,[cx,cy],([rx,ry] or r),ang,leng,lScale,w
//where ang and leng are
this.aArrow=function(a,b,c,d,e,f,g,h){
if(b.orig){
return new ArcArrow(a,[b.orig[0]+c,b.orig[1]],[d*b.px,d],e,f,g,h);
}else{
if(c.length)
return new ArcArrow(a,b,c,d,e,f,g);
else
return new ArcArrow(a,b,[c,c],d,e,f,g);
}
}
this.wheel = function(vt,vr,name,A,rest,r,bracket){return new Wheel(vt,vr,name,A,rest,r,bracket)}
this.vessel=function(p,s,open,label){return new Vessel(p,s,open,label)}
this.pipe=function(p1,p2,w,label){return new Pipe(p1,p2,w,label)}
this.mixer=function(p1,p2,w,label){return new Mixer(p1,p2,w,label)}
this.motor=function(vr,vi,p,s,dir){return new Motor(0,vr,vi,p,s,dir)};
this.galv= function(vr,vi,p,s,dir){return new Motor(1,vr,vi,p,s,dir)};
this.speaker= function(vm,vb,vi,p,s,angle,dir){return new Speaker(vm,vb,vi,p,s,angle,dir)};
/* ---------------------------------------- */
//used by spring(), dash(), and rope()
function mkLink(type,name,axis,mA,mB,off){
var v1,v2,o1,o2,h1,h2; //Y var, offset, home
if(typeof mA=='object'){
v1=mA.v;
o1=mA.w/2; //half the width of the mass.
h1=mA.rest;
}else{
v1=-1; //-1 means it's not assigned to a Y output; stationary
o1=0;
h1=mA;
}
if(typeof mB=='object'){
v2=mB.v;
o2=mB.w/2;
h2=mB.rest;
}else{
v2=-1;
o2=0;
h2=mB;
}
//make sure p1<p2
if(h2>h1)
return new Linkage(type,name,axis,v1,v2,h1+o1,h2-o2,off);
else
return new Linkage(type,name,axis,v2,v1,h2+o2,h1-o1,off);
}
/* there are several ways to define labels:
'L' or ['L'] - Label, placed in the element's default spot
['L', 'Q'] (where Q is n,s,e,w) - placed to the North, South, etc. as defined by the element
['L', n] - if n==0, placed at the default location.
If n==1, another default location, depending on the element, e.g. the other side (for circuit elements)
['L', [x,y]] - placed at a fixed [x,y] offset from the center of the element
['L', [x,y],align] with alignment according to align, defaulting to 0 (middle)
ther'll be a standard way for elements to specify N,S,E,W, and default, offsets:
it's an array:
0: N
1: S
2: E
3: W
4: default
5: -default
For example: [[ 0,-20], //n
[ 0, 20], //s
[ 30, 0], //e
[-30, 0], //w
[ 0, 20, 0], //d //the third number is alignment. For N,S,E,W, this will default to 0,0,1,-1
[ 0,-20, 0]] //d2
we'll also need a way of specifying text alignment.
perhaps this funciton could just return a Raphael.text object.
the ploblem with that is if there's a label that moves differently depending on location...
maybe it will return:
[x,y,label,align], where align is middle, start, or end
*/
function doLabel(label,defs,p){
var txt; //text
var off; //offset
var aln; //allignment
if(typeof label=='object'){ //not just a string
txt=label[0];
if(typeof label[1]=='object'){ //it's [x,y]. Our job is easy
off=label[1];
aln=label[2]||0; //default to 0 (centered)
}else if(typeof label[1]=='string'){//it's n,s,e,w
switch(label[1].toUpperCase()){
case 'N': off=defs[0]; aln= 0; break;
case 'S': off=defs[1]; aln= 0; break;
case 'E': off=defs[2]; aln= 1; break;
case 'W': off=defs[3]; aln=-1; break;
default : off=defs[4]; aln=defs[4][2];
}
}else{ //it's either 0, 1, or undefined, for the defaults
if(label[1]){ //not 0 or undefined --default2
off=defs[5]; aln=defs[5][2];
}else{ //0 or undefined -- default
off=defs[4]; aln=defs[4][2];
}
}
}else{//just a string (or number); use default
txt=label; off=defs[4]; aln=defs[4][2];
}
if(txt===undefined)txt="";
var anch; //anchor
switch(aln){
case 1: anch='start'; break;
case -1: anch='end' ; break;
case 0:
default: anch='middle';
}
return canv.text(p[0]+off[0],p[1]+off[1],txt)
.attr('text-anchor',anch)
.attr(textAttribs);
}
//this seemed like a good idea at the time...
function vect(x,y){return {x:x,y:y}}
/////TRANSLATING AND THERMAL SYSTEMS/////
//A linear axis is used by translating systems
function Axis(O,dir){
var angle,D;
if((typeof dir)=='number'){
angle=dir;
D=vect(Math.dcos(dir),Math.dsin(dir));
}else{
D=dir;
angle=Math.atan2(dir.y,dir.x)/Math.PI*180;