-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathCellMachine.js
executable file
·1439 lines (1237 loc) · 39.9 KB
/
CellMachine.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
"use strict";
//--------------------------------------
function Columns() {
this.minIndex = Infinity;
this.maxIndex = -Infinity;
this.storage = [];
}
Columns.prototype.getColumn = function Columns_getColumn(i,create) {
if (typeof(create) === 'undefined') {
create = true;
}
if (!create && (i < this.minIndex || i > this.maxIndex)) {
return false;
}
if (this.maxIndex < this.minIndex) {
this.minIndex = this.maxIndex = i;
this.storage = [[]];
}
while (i < this.minIndex) {
this.minIndex -= 1;
this.storage.unshift([]);
}
while (i > this.maxIndex) {
this.maxIndex += 1;
this.storage.push([]);
}
return this.storage[i - this.minIndex];
};
//--------------------------------------
const NEEDLE_REGEX = /^([fb]s?)([-+]?\d+)$/;
function previousNeedle(n) {
let m = n.match(NEEDLE_REGEX);
console.assert(m, "previousNeedle must be passed needle; got '" + n + "' instead.");
return m[1] + (parseInt(m[2])-1).toString();
}
function nextNeedle(n) {
let m = n.match(NEEDLE_REGEX);
console.assert(m, "nextNeedle must be passed needle; got '" + n + "' instead.");
return m[1] + (parseInt(m[2])+1).toString();
}
function needleIndex(n) {
let m = n.match(NEEDLE_REGEX);
console.assert(m, "needleIndex must be passed needle; got '" + n + "' instead.");
return 2*parseInt(m[2]);
}
function needleBed(n) {
let m = n.match(NEEDLE_REGEX);
console.assert(m, "needleBed must be passed needle; got '" + n + "' instead.");
return m[1];
}
//the index of the yarn column before needle n if making a stitch in direction d:
function yarnBeforeIndex(d, n) {
if (d === '+') {
return needleIndex(n) - 1;
} else if (d === '-') {
return needleIndex(n) + 1;
} else {
console.assert(d === '+' || d === '-', "Direction must be + or -.");
}
}
//the index of the yarn just after needle n if making a stitch in direction d:
function yarnAfterIndex(d, n) {
if (d === '+') {
return needleIndex(n) + 1;
} else if (d === '-') {
return needleIndex(n) - 1;
} else {
console.assert(d === '+' || d === '-', "Direction must be + or -.");
}
}
//--------------------------------------
function YarnCell() {
this.y = 0;
//port layout in cell:
// ^- ^+
// +----|-----|----+
// | |
//- - x- X- X+ x+ - +
// | |
// +----|-----|----+
// v- v+
//
// ('o' ports are in the same place as 'x' ports)
// ('o' ports point toward us, 'x' point in)
this.ports = {
'^-':[], '^+':[],
'-':[], 'x-':[], 'X-':[], 'X+':[], 'x+':[], '+':[],
'o-':[], 'O-':[], 'O+':[], 'o+':[],
'v-':[], 'v+':[]
};
this.segs = []; //like: {cn:'A', from:'^-', to:'x+'}
this.dir = '';
}
YarnCell.prototype.addSeg = function YarnCell_addSeg(yarn, from, to) {
console.assert((from == '') || from in this.ports, "Wanted be valid from port, got '" + from + "'.");
console.assert((to == '') || to in this.ports, "Wanted be valid to port, got '" + to + "'.");
this.segs.push({cn:yarn, from:from, to:to});
if (from !== '') this.addOut_(from, yarn);
if (to !== '') this.addOut_(to, yarn);
};
YarnCell.prototype.addOut_ = function YarnCell_addOut(dir, yarn) {
console.assert(dir in this.ports, "Wanted be valid direction, got '" + dir + "'.");
this.ports[dir].push(yarn);
};
YarnCell.prototype.canAbsorb = function YarnCell_canAbsorb(below) {
//NOTE: doesn't take into account yarn starts! (Though I'm not 100% sure there is a way for this to go wrong.)
//NOTE: doesn't take into account yarns crossing themselves! (Again, not sure this ever happens.)
//Don't collapse if any side ports overlap:
if (['-','+','x-','X-','X+','x+','o-','O-','O+','o+'].some(function(pn){
return below.ports[pn].length && this.ports[pn].length;
}, this)) {
//console.log(" NO: overlap"); //DEBUG
return false;
}
return true;
};
YarnCell.prototype.absorb = function YarnCell_absorb(below) {
/*
//DEBUG:
console.log("Absorb:");
//console.log(JSON.stringify(this.segs));
//console.log(JSON.stringify(below.segs));
console.log(
"^" + JSON.stringify(this.ports['^-'])
+ JSON.stringify(this.ports['^+'])
+ " v"
+ JSON.stringify(this.ports['v-'])
+ JSON.stringify(this.ports['v+'])
);
console.log(
"^" + JSON.stringify(below.ports['^-'])
+ JSON.stringify(below.ports['^+'])
+ " v"
+ JSON.stringify(below.ports['v-'])
+ JSON.stringify(below.ports['v+'])
);
*/
let connect = { '-':{}, '+':{} };
let segs = [];
below.segs.forEach(function(seg){
console.assert(['^-','^+'].indexOf(seg.from) === -1, "always top to");
if (seg.to === '^-') {
console.assert(!(seg.cn in connect['-']), "no dulicate exist please");
connect['-'][seg.cn] = seg.from;
} else if (seg.to === '^+') {
console.assert(!(seg.cn in connect['+']), "no dulicate exist please");
connect['+'][seg.cn] = seg.from;
} else {
segs.push(seg);
}
}, this);
this.segs.forEach(function(seg){
console.assert(['v-','v+'].indexOf(seg.to) === -1, "always bottom from");
if (seg.from === 'v-') {
console.assert(seg.cn in connect['-'], "must connect");
seg.from = connect['-'][seg.cn];
delete connect['-'][seg.cn];
} else if (seg.from === 'v+') {
console.assert(seg.cn in connect['+'], "must connect");
seg.from = connect['+'][seg.cn];
delete connect['+'][seg.cn];
}
segs.push(seg);
}, this);
for (let cn in connect['-']) {
console.assert(false, "Segment '" + cn + "' is dangling on - side");
}
for (let cn in connect['+']) {
console.assert(false, "Segment '" + cn + "' is dangling on + side");
}
//record port orders for later use:
let orders = {'v-':[], 'v+':[]};
for (let pn in this.ports) {
if (pn === 'v-' || pn === 'v+') continue;
orders[pn] = this.ports[pn].slice();
}
for (let pn in below.ports) {
if (pn === '^-' || pn === '^+') continue;
if (below.ports[pn].length === 0) continue;
console.assert(orders[pn].length === 0, "no overlap");
orders[pn] = below.ports[pn].slice();
}
//rebuild from segs:
for (let pn in this.ports) {
this.ports[pn].splice(0, this.ports[pn].length);
console.assert(this.ports[pn].length === 0, "did clear");
}
this.segs.splice(0, this.segs.length);
console.assert(this.segs.length === 0, "did clear");
segs.forEach(function(seg){
this.addSeg(seg.cn, seg.from, seg.to);
}, this);
//apply port orders:
for (let pn in orders) {
console.assert(this.ports[pn].length == orders[pn].length, "same count");
this.ports[pn].forEach(function(cn){
console.assert(orders[pn].indexOf(cn) !== -1, "same yarns");
}, this);
this.ports[pn] = orders[pn];
}
/*
//DEBUG
//console.log(" --> " + JSON.stringify(this.segs));
console.log(" ---> " +
"^" + JSON.stringify(this.ports['^-'])
+ JSON.stringify(this.ports['^+'])
+ " v"
+ JSON.stringify(this.ports['v-'])
+ JSON.stringify(this.ports['v+'])
);
*/
};
YarnCell.prototype.desc = function YarnCell_desc() {
let bits = 0;
bits |= (this.ports['-'].length ? 1 : 0);
bits |= (this.ports['+'].length ? 2 : 0);
bits |= (this.ports['v'].length ? 4 : 0);
bits |= (this.ports['^'].length ? 8 : 0);
const chars = [
' ', '╴', '╶', '─',
'╷', '╮', '╭', '┬',
'╵', '╯', '╰', '┴',
'│', '┤', '├', '┼'
];
return chars[bits];
};
function LoopCell(type) {
this.type = type;
this.y = 0;
this.dir = '';
this.ports = { '-':[], '+':[], 'v':[], '^':[], 'x':[], 'o':[] };
}
LoopCell.prototype.addOut = function LoopCell_addOut(dir, yarn) {
console.assert(dir in this.ports, "Wanted be valid direction, got '" + dir + "'.");
this.ports[dir].push(yarn);
};
LoopCell.prototype.canAbsorb = function LoopCell_canAbsorb(below) {
return false;
};
LoopCell.prototype.desc = function LoopCell_desc() {
const map = {
m:'┄',
t:'∧',
k:'∩',
x:'╻',
X:'╹',
s:'┰',
S:'┸'
};
if (this.type in map) {
return map[this.type];
} else {
return this.type;
}
};
//--------------------------------------
function CellMachine() {
this.carriers = []; //carriers, front-to-back. Each is {name:"A", after:{n:, d:}, index:}
this.beds = {
b:new Columns(),
bs:new Columns(),
fs:new Columns(),
f:new Columns()
};
this.crosses = []; //<-- yarn crossings between beds
this.topRow = 0;
this.styles = {}; //<-- space-separated carrier sets => {color: , ...} objects; set with x-vis-color command
this.racking = 0.0; //<-- racking, N or N + 0.25
this.defaultStyles = {};
this.currentSource = ""; //<-- current source line from ;!source: comments; will be passed
};
//Helpers:
CellMachine.prototype.getCarrier = function CellMachine_getCarrier(cn) {
let idx = -1;
this.carriers.forEach(function(c,ci){
if(c.name === cn){
idx = ci;
}
}, this);
console.assert(idx >= 0, "Carrier exists");
return this.carriers[idx];
};
CellMachine.prototype.dump = function CellMachine_dump() {
//dump to ascii grid.
let minIndex = Infinity;
let maxIndex = -Infinity;
for (let bn in this.beds) {
minIndex = Math.min(minIndex, this.beds[bn].minIndex);
maxIndex = Math.max(maxIndex, this.beds[bn].maxIndex);
}
if (minIndex > maxIndex) return;
console.log("Raster is [" + minIndex + "," + maxIndex + "]x[" + 0 + "," + this.topRow + "]:");
let outRows = [];
let rasterWidth = maxIndex+1-minIndex;
['f','b'].forEach(function(bn) {
let outIndex = 0;
function outRow(row) {
if (outIndex >= outRows.length) {
outRows.push("");
}
if (outRows[outIndex] != "") outRows[outIndex] += " | ";
outRows[outIndex] += row;
outIndex += 1;
}
let raster = new Array(rasterWidth * (this.topRow+1));
for (let i = minIndex; i <= maxIndex; ++i) {
this.beds[bn].getColumn(i).forEach(function(c){
let y = c.y;
let x = i - minIndex;
console.assert(typeof(raster[y * rasterWidth + x]) === 'undefined', "no stacks");
raster[y * rasterWidth + x] = c.desc();
});
}
let maxY = Math.min(2000, this.topRow); //DEBUG -- should be this.topRow
for (let y = maxY; y >= 0; --y) {
let row = "";
for (let x = 0; x < rasterWidth; ++x) {
if (typeof(raster[y * rasterWidth + x]) !== 'undefined') {
row += raster[y * rasterWidth + x];
} else {
row += ' ';
}
}
outRow(row);
}
}, this);
console.log(outRows.join("\n"));
};
CellMachine.prototype.addCells = function CellMachine_addCells(b, list, cross) {
console.assert(b in this.beds, "Wanted valid bed, got '" + b + "'.");
let y = this.topRow;
if (typeof(cross) !== 'undefined') {
let bi, fi;
let bp = '';
let fp = '';
if (cross.b[0] === 'b' && cross.b2[0] === 'f') {
bi = cross.i; fi = cross.i2;
if ('port' in cross) bp = cross.port;
if ('port2' in cross) fp = cross.port2;
} else { console.assert(cross.b[0] === 'f' && cross.b2[0] === 'b', "must cross f <-> b");
fi = cross.i; bi = cross.i2;
if ('port' in cross) fp = cross.port;
if ('port2' in cross) bp = cross.port2;
}
const px = {
'':0.5,
'o-':0.00, 'x-':0.00,
'O-':0.25, 'X-':0.25,
'O+':0.50, 'X+':0.50,
'o+':0.75, 'x+':0.75
};
console.assert(bp in px && fp in px, "port names should exist");
let bx = bi + px[bp];
let fx = fi + px[fp];
cross.bx = bx;
cross.fx = fx;
this.crosses.some(function(cross2){
if (cross2.y < y) return true; //early out when reach earlier portion of list
let bx2 = cross2.bx;
let fx2 = cross2.fx;
if (fx < fx2 && bx < bx2) return;
if (fx > fx2 && bx > bx2) return;
y = cross2.y + 1;
});
}
list.forEach(function(icell){
let bedName = ('bed' in icell ? icell.bed : b);
{ //check column containing cell:
let bed = this.beds[bedName];
let column = bed.getColumn(icell.i);
if (column.length) {
let back = column[column.length-1];
if (back.y >= y) {
y = back.y;
if (!icell.cell.canAbsorb(back)) {
y = back.y + 1;
}
}
}
}
{ //check sliders/hook of column containing cell:
let bedName2 = (bedName.length == 2 ? bedName[0] : bedName + 's');
console.assert(bedName2 in this.beds);
let bed = this.beds[bedName2];
let column = bed.getColumn(icell.i);
if (column.length) {
let back = column[column.length-1];
if (back.y >= y) {
y = back.y + 1;
}
}
}
}, this);
list.forEach(function(icell){
let bed = this.beds[('bed' in icell ? icell.bed : b)];
icell.cell.y = y;
icell.cell.styles = this.styles;
let column = bed.getColumn(icell.i);
function dump() {
if ('v' in icell.cell.ports) {
console.log("Adding " + JSON.stringify(icell.cell.ports['v']) + " over " + (column.length ? JSON.stringify(column[column.length-1].ports['^']) : "empty column"));
} else {
console.log("Adding "
+ JSON.stringify(icell.cell.ports['v-'])
+ " | " + JSON.stringify(icell.cell.ports['v+'])
+ " over "
+ (column.length ?
JSON.stringify(column[column.length-1].ports['^-'])
+ " | " + JSON.stringify(column[column.length-1].ports['^+'])
: "empty column"));
}
return false;
}
//Add empty cells to hold trailing loops/yarns:
if (icell.i % 2 === 0) {
let cs = icell.cell.ports['v'];
//had better be exactly the same stack from below:
if (cs.length) {
console.assert((column.length && JSON.stringify(column[column.length-1].ports['^']) === JSON.stringify(cs)) || dump(), "loops out should always be exactly loops in.");
while (column[column.length-1].y + 1 < y) {
let empty = new LoopCell('m');
empty.y = column[column.length-1].y + 1;
cs.forEach(function (cn) {
empty.addOut('v', cn);
empty.addOut('^', cn);
});
empty.styles = column[column.length-1].styles;
column.push(empty);
}
} else {
console.assert(column.length === 0 || column[column.length-1].ports['^'].length === 0 || dump(), "loops out should match loops in.");
}
} else {
let csL = icell.cell.ports['v-'];
let csR = icell.cell.ports['v+'];
if (csL.length || csR.length) {
console.assert((column.length
&& JSON.stringify(column[column.length-1].ports['^-']) === JSON.stringify(csL)
&& JSON.stringify(column[column.length-1].ports['^+']) === JSON.stringify(csR) ) || dump(), "yarn out should always be exactly yarn in.");
//had better be exactly the same stack from below:
while (column[column.length-1].y + 1 < y) {
let empty = new YarnCell();
empty.y = column[column.length-1].y + 1;
csL.forEach(function (cn) {
empty.addSeg(cn, 'v-', '^-');
});
csR.forEach(function (cn) {
empty.addSeg(cn, 'v+', '^+');
});
empty.styles = column[column.length-1].styles;
column.push(empty);
}
} else {
console.assert(column.length === 0 || (
column[column.length-1].ports['^-'].length === 0
&& column[column.length-1].ports['^+'].length === 0
) || dump(), "yarns out should always be exactly yarns in.");
}
}
if (column.length) {
let back = column[column.length-1];
if (back.y === y) {
icell.cell.absorb(back);
column.pop();
}
}
icell.cell.source = this.currentSource;
column.push(icell.cell);
}, this);
this.topRow = y;
if (typeof(cross) !== 'undefined') {
cross.y = y;
cross.styles = this.styles;
//DEBUG: console.log(cross.b + cross.i + " -> " + cross.b2 + cross.i2 + " @ " + cross.y + " " + JSON.stringify(cross.yarns));
this.crosses.unshift(cross); //keep list sorted in descending order
}
};
//helper: order port based on carrier order:
CellMachine.prototype.sortPort = function(port) {
let me = this;
port.sort(function(a,b){ return me.getCarrier(a).index - me.getCarrier(b).index; });
for (let i = 1; i < port.length; ++i) {
console.assert(this.getCarrier(port[i-1]).index < this.getCarrier(port[i]).index, "port is, indeed, sorted.");
}
};
//bring carriers to *before* n in direction d:
CellMachine.prototype.bringCarriers = function CellMachine_bringCarriers(d, n, cs) {
cs.forEach(function(cn){
console.assert('in' in this.getCarrier(cn), "Can only bring carriers that are in.");
}, this);
//New: gather up carriers and move 'em on over, ending with upward yarn on the proper needle and everything.
if (cs.length === 0) return;
//goal: move all carriers to the given side of the given (front bed) index:
let targetIndex;
let targetSide;
//ports used in case of crossing:
let crossFrom = '';
let crossTo = '';
if (needleBed(n)[0] === 'f') {
targetIndex = yarnBeforeIndex(d, n);
targetSide = d;
} else { console.assert(needleBed(n)[0] === 'b', "must be on 'f*' or 'b*' bed.");
//pick the index across from the needle's before at the current racking:
targetIndex = yarnBeforeIndex(d, 'f' + (needleIndex(n)/2 + Math.floor(this.racking)));
if (this.racking === Math.floor(this.racking)) {
crossFrom = 'x' + d;
crossTo = 'o' + d;
targetSide = d;
} else {
console.assert(Math.floor(this.racking) + 0.25 === this.racking, "Integer or quarter pitch only.");
//at quarter pitch, the bins line up a bit differently:
// +|b0|- +|b1|-
// +|f0|- +|f1|- +|
if (d === '+') {
targetIndex += 2; //(b0,+) would yield the bin left of f0, move to right
targetSide = '-'; //target left side
crossFrom = 'X-'; //cross on inside of lanes
crossTo = 'o+'; //arrive at edge (not that it matters)
} else {
//(b0,-) would yield the bin right of f0
targetSide = '+'; //target right side of bin
crossFrom = 'X+'; //cross on inside of lanes
crossTo = 'o-'; //arrive at edge (not that it matters)
}
}
}
//figure out range of where carriers are parked:
let minIndex = targetIndex;
let maxIndex = targetIndex;
cs.forEach(function(cn){
let c = this.getCarrier(cn);
if (c.after) {
console.assert(needleBed(c.after.n) === 'f', "Carriers must always be parked on the front.");
let index = yarnAfterIndex(c.after.d, c.after.n);
minIndex = Math.min(minIndex, index);
maxIndex = Math.max(maxIndex, index);
}
}, this);
let cells = [];
//left-to-right sweep:
let movingRight = [];
for (let i = minIndex; i < targetIndex; ++i) {
let front = this.beds['f'].getColumn(i);
if (i % 2 === 0) {
//loop tile
let up = (front.length ? front[front.length-1].ports['^'] : []);
let miss = new LoopCell('m');
miss.dir = '+';
up.forEach(function(cn){
miss.addOut('v', cn);
miss.addOut('^', cn);
}, this);
movingRight.forEach(function(cn) {
miss.addOut('-', cn);
miss.addOut('+', cn);
}, this);
cells.push({i:i, cell:miss});
} else {
//yarn tile
let cell = new YarnCell();
cell.dir = '+';
let movingFrom = {};
movingRight.forEach(function(cn){
movingFrom[cn] = '-';
});
['-','+'].forEach(function(side){
let up = (front.length ? front[front.length-1].ports['^'+side] : []);
up.forEach(function(cn){
if (cs.indexOf(cn) === -1) {
cell.addSeg(cn, 'v'+side, '^'+side);
} else {
movingFrom[cn] = 'v'+side;
console.assert(movingRight.indexOf(cn) === -1, "can't get a yarn twice");
movingRight.push(cn);
}
}, this);
}, this);
movingRight.sort(function(a,b){
return cs.indexOf(a) - cs.indexOf(b);
});
for (let i = 1; i < movingRight.length; ++i) {
console.assert(cs.indexOf(movingRight[i-1]) < cs.indexOf(movingRight[i]), "the plating sort is working.");
}
movingRight.forEach(function(cn){
cell.addSeg(cn, movingFrom[cn], '+');
}, this);
this.sortPort(cell.ports['v+']);
this.sortPort(cell.ports['v-']);
cells.push({i:i, cell:cell});
}
}
//right-to-left sweep:
let movingLeft = [];
for (let i = maxIndex; i > targetIndex; --i) {
let front = this.beds['f'].getColumn(i);
if (i % 2 === 0) {
//loop tile
let up = (front.length ? front[front.length-1].ports['^'] : []);
let miss = new LoopCell('m');
miss.dir = '-';
up.forEach(function(cn){
miss.addOut('v', cn);
miss.addOut('^', cn);
}, this);
movingLeft.forEach(function(cn) {
miss.addOut('+', cn);
miss.addOut('-', cn);
}, this);
cells.push({i:i, cell:miss});
} else {
//yarn tile
let cell = new YarnCell();
cell.dir = '-';
let movingFrom = {};
movingLeft.forEach(function(cn){
movingFrom[cn] = '+';
});
['-','+'].forEach(function(side){
let up = (front.length ? front[front.length-1].ports['^'+side] : []);
up.forEach(function(cn){
if (cs.indexOf(cn) === -1) {
cell.addSeg(cn, 'v'+side, '^'+side);
} else {
movingFrom[cn] = 'v'+side;
console.assert(movingLeft.indexOf(cn) === -1, "can't get a yarn twice");
movingLeft.push(cn);
}
}, this);
}, this);
movingLeft.sort(function(a,b){
return cs.indexOf(a) - cs.indexOf(b);
});
for (let i = 1; i < movingLeft.length; ++i) {
console.assert(cs.indexOf(movingLeft[i-1]) < cs.indexOf(movingLeft[i]), "the plating sort is working.");
}
movingLeft.forEach(function(cn){
cell.addSeg(cn, movingFrom[cn], '-');
}, this);
this.sortPort(cell.ports['v+']);
this.sortPort(cell.ports['v-']);
cells.push({i:i, cell:cell});
}
}
{ //turn everything upward:
let turn = new YarnCell();
let front = this.beds['f'].getColumn(targetIndex);
let upLeft = (front.length ? front[front.length-1].ports['^-'] : []);
let upRight = (front.length ? front[front.length-1].ports['^+'] : []);
let outSide = '^' + targetSide;
upLeft.forEach(function(cn){
if (cs.indexOf(cn) !== -1) {
turn.addSeg(cn, 'v-', outSide);
} else {
turn.addSeg(cn, 'v-', '^-');
}
}, this);
upRight.forEach(function(cn){
if (cs.indexOf(cn) !== -1) {
turn.addSeg(cn, 'v+', outSide);
} else {
turn.addSeg(cn, 'v+', '^+');
}
}, this);
movingLeft.forEach(function(cn){
turn.addSeg(cn, '+', outSide);
}, this);
movingRight.forEach(function(cn){
turn.addSeg(cn, '-', outSide);
}, this);
//start any carriers not already mentioned:
cs.forEach(function(cn){
if (turn.ports[outSide].indexOf(cn) === -1) {
turn.addSeg(cn, '', outSide);
//add an 'after' field just to be sure:
let c = this.getCarrier(cn);
console.assert(!('after' in c), "if not gotten, must not have been used yet");
c.after = {d:(targetSide === '+' ? '-' : '+'), n:'f' + Math.floor(targetIndex/2)};
}
}, this);
this.sortPort(turn.ports[outSide]);
cells.push({i:targetIndex, cell:turn});
}
/*
//DEBUG:
console.log("----");
cells.forEach(function(cell){
if ('^-' in cell.cell.ports) {
console.log(
"^" + JSON.stringify(cell.cell.ports['^-'])
+ JSON.stringify(cell.cell.ports['^+'])
+ " v"
+ JSON.stringify(cell.cell.ports['v-'])
+ JSON.stringify(cell.cell.ports['v+'])
);
}
});
console.log(cells); //DEBUG
*/
this.addCells('f', cells);
//if needed, bridge to back:
if (needleBed(n) !== 'f') {
console.assert(needleBed(n) === 'b', "only f/b supported.");
//make bridge to the back bed:
let cells = [];
let toBack = new YarnCell();
toBack.dir = d;
let front = this.beds['f'].getColumn(targetIndex);
//console.log(JSON.stringify(front)); //DEBUG
let found = 0;
['-','+'].forEach(function(side){
let up = (front.length ? front[front.length-1].ports['^'+side] : []);
//console.log(side + ": " + JSON.stringify(up)); //DEBUG
up.forEach(function(cn){
if (cs.indexOf(cn) !== -1) {
console.assert(targetSide === side, "all yarns should be on correct side");
++found;
} else {
toBack.addSeg(cn, 'v'+side, '^'+side);
}
}, this);
}, this);
//console.log(cs); //DEBUG
console.assert(found === cs.length, "got all carriers");
cs.forEach(function(cn){
toBack.addSeg(cn, 'v'+targetSide, crossFrom);
}, this);
cells.push({bed:'f', i:targetIndex, cell:toBack});
let fromFront = new YarnCell();
cs.forEach(function(cn){
fromFront.addSeg(cn, crossTo, '^'+d); //not targetSide because of quarter pitch racking
}, this);
cells.push({bed:'b', i:yarnBeforeIndex(d,n), cell:fromFront});
const cross = {
yarns:cs.slice(),
b:'f', i:targetIndex, port:crossFrom,
b2:'b', i2:yarnBeforeIndex(d,n), port2:crossTo,
type:'y'
};
this.addCells('f', cells, cross);
}
//mark carriers:
cs.forEach(function(cn){
let c = this.getCarrier(cn);
console.assert('after' in c, "All moved carriers should be after something.");
delete c.after;
//mark all carriers as before something, since they just got moved:
c.before = {d:d, n:n};
}, this);
};
CellMachine.prototype.makeTurnBefore = function CellMachine_makeTurnBefore(d, n, cs, cells) {
//to be used after bringCarriers -- makes a turn containing all the carriers in cs,
//stores it into cells.
//Turn carriers toward the needle:
if (cs.length) {
let turn = new YarnCell();
turn.dir = d;
let column = this.beds[needleBed(n)].getColumn(yarnBeforeIndex(d,n));
console.assert(column.length, "carriers must be here already");
let turned = 0;
['-','+'].forEach(function(side){
column[column.length-1].ports['^'+side].forEach(function (cn) {
if (cs.indexOf(cn) === -1) {
turn.addSeg(cn, 'v'+side, '^'+side);
} else {
console.assert(side === d, "should already be on the right side");
++turned;
turn.addSeg(cn, 'v'+side, d);
}
}, this);
}, this);
console.assert(turned === cs.length, "turned all the yarns");
cells.push({i:yarnBeforeIndex(d, n), cell:turn});
}
};
CellMachine.prototype.makeAfter = function CellMachine_makeAfter(d, n, cs, cells, cross) {
//to be used after building the yarn face
//turn carriers back up:
if (cs.length) {
let turn = new YarnCell();
turn.dir = d;
let column = this.beds[needleBed(n)].getColumn(yarnAfterIndex(d,n));
if (column.length) {
['-','+'].forEach(function(side){
column[column.length-1].ports['^'+side].forEach(function (cn) {
console.assert(cs.indexOf(cn) === -1, "shouldn't run into same yarn");
turn.addSeg(cn, 'v'+side, '^'+side);
}, this);
}, this);
}
let outSide = (d === '+' ? '-' : '+');
cs.forEach(function(cn){
turn.addSeg(cn, outSide, '^'+outSide);
}, this);
this.sortPort(turn.ports['^'+outSide]);
cells.push({i:yarnAfterIndex(d, n), cell:turn});
}
// if (typeof(cross) === 'undefined'){
// this.addCells(needleBed(n), cells, cross);
// }
this.addCells(needleBed(n), cells, cross);
let frontD;
let frontN;
let crossTo = '';
let crossFrom = '';
//mark carriers:
if (needleBed(n)[0] === 'f') {
frontD = d;
frontN = n;
} else { console.assert(needleBed(n)[0] === 'b', "Only f/b at the moment");
frontD = d;
if (this.racking === Math.floor(this.racking)) {
//aligned racking:
frontN = 'f' + (needleIndex(n)/2 + Math.floor(this.racking));
crossFrom = 'o' + (d === '+' ? '-' : '+');
crossTo = 'x' + (d === '+' ? '-' : '+');
} else { console.assert(Math.floor(this.racking)+0.25 === this.racking, "quarter pitch please");
//unaligned (e.g. quarter pitch) racking:
if (d === '+') {
frontN = 'f' + (needleIndex(n)/2 + Math.floor(this.racking) + 1);
frontD = '-';
crossFrom = 'o-';
crossTo = 'X+';
} else { console.assert(d === '-', "+/- only");
frontN = 'f' + (needleIndex(n)/2 + Math.floor(this.racking));
frontD = '+';
crossFrom = 'o+';
crossTo = 'X-';
}
}
if (cs.length) {
//detour: also add bridge from back bed
let cells = [];
let toFront = new YarnCell();
toFront.dir = d;
cs.forEach(function(cn){
toFront.addSeg(cn,'v' + (d === '+' ? '-' : '+'), crossFrom);
}, this);
cells.push({bed:'b', i:yarnAfterIndex(d,n), cell:toFront});
let fromBack = new YarnCell();
fromBack.dir = d;
let front = this.beds['f'].getColumn(yarnAfterIndex(frontD, frontN));
['-','+'].forEach(function(side){
(front.length ? front[front.length-1].ports['^' + side] : []).forEach(function(cn) {
console.assert(cs.indexOf(cn) === -1, "shouldn't be over here");
fromBack.addSeg(cn, 'v'+side, '^'+side);
}, this);
}, this);
cs.forEach(function(cn){
fromBack.addSeg(cn, crossTo, '^' + (frontD === '+' ? '-' : '+'));
}, this);
this.sortPort(fromBack.ports['^' + (frontD === '+' ? '-' : '+')]);
cells.push({bed:'f', i:yarnAfterIndex(frontD, frontN), cell:fromBack});
const cross = {
yarns:cs.slice(),
b:'b', i:yarnAfterIndex(d,n), port:crossFrom,
b2:'f', i2:yarnAfterIndex(frontD,frontN), port2:crossTo,
type:'y'
};
this.addCells('f', cells, cross);
}
}
//record 'after' info:
cs.forEach(function(cn){
let c = this.getCarrier(cn);
console.assert('before' in c, "must have been brought");
console.assert(!('after' in c), "must have been brought, thus no after");
delete c.before;
c.after = {d:frontD, n:frontN};
}, this);
};