-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathcompiler.js
3446 lines (3036 loc) · 135 KB
/
compiler.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 isColor(str) {
str = str.trim();
if (str in colorPalettes.arnecolors)
return true;
if (REGEX_HEX.test(str))
return true;
if (str === "transparent")
return true;
return false;
}
function colorToHex(palette, str) {
str = str.trim();
if (str in palette) {
return palette[str];
}
return str;
}
function generateSpriteMatrix(dat) {
let result = [];
for (let i = 0; i < dat.length; i++) {
let row = [];
for (let j = 0; j < dat.length; j++) {
let ch = dat[i].charAt(j);
if (ch === '.') {
row.push(-1);
} else {
row.push(ch);
}
}
result.push(row);
}
return result;
}
let debugMode;
let colorPalette;
function generateExtraMembers(state) {
//annotate objects with layers
//assign ids at the same time
state.idDict = [];
let idcount = 0;
for (let layerIndex = 0; layerIndex < state.collisionLayers.length; layerIndex++) {
for (let j = 0; j < state.collisionLayers[layerIndex].length; j++) {
let n = state.collisionLayers[layerIndex][j];
if (n in state.objects) {
let o = state.objects[n];
o.layer = layerIndex;
o.id = idcount;
state.idDict[idcount] = n;
idcount++;
}
}
}
//set object count
state.objectCount = idcount;
//calculate blank mask template
let layerCount = state.collisionLayers.length;
let blankMask = [];
for (let i = 0; i < layerCount; i++) {
blankMask.push(-1);
}
// how many words do our bitvecs need to hold?
STRIDE_OBJ = Math.ceil(state.objectCount / 32) | 0;
STRIDE_MOV = Math.ceil(layerCount / 5) | 0;
LAYER_COUNT = layerCount;
state.STRIDE_OBJ = STRIDE_OBJ;
state.STRIDE_MOV = STRIDE_MOV;
state.LAYER_COUNT = LAYER_COUNT;
RebuildGameArrays();
//get colorpalette name
debugMode = false;
verbose_logging = false;
throttle_movement = false;
colorPalette = colorPalettes.arnecolors;
for (let i = 0; i < state.metadata.length; i += 2) {
let key = state.metadata[i];
let val = state.metadata[i + 1];
if (key === 'color_palette') {
if (val in colorPalettesAliases) {
val = colorPalettesAliases[val];
}
if (colorPalettes[val] === undefined) {
logError('Palette "' + val + '" not found, defaulting to arnecolors.', 0);
} else {
colorPalette = colorPalettes[val];
}
} else if (key === 'debug') {
if (IDE && unitTesting === false) {
debugMode = true;
cache_console_messages = true;
}
} else if (key === 'verbose_logging') {
if (IDE && unitTesting === false) {
verbose_logging = true;
cache_console_messages = true;
}
} else if (key === 'throttle_movement') {
throttle_movement = true;
}
}
let glyphOrder = [];
let glyphDict = {};
//convert colors to hex
const state_object_keys = Object.keys(state.objects);
const state_object_keys_l = state_object_keys.length;
for (let k_i = 0; k_i < state_object_keys_l; k_i++) {
const n = state_object_keys[k_i];
//convert color to hex
let o = state.objects[n];
if (o.colors.length > 10) {
logError("a sprite cannot have more than 10 colors. Why you would want more than 10 is beyond me.", o.lineNumber + 1);
}
for (let i = 0; i < o.colors.length; i++) {
let c = o.colors[i];
if (isColor(c)) {
c = colorToHex(colorPalette, c);
o.colors[i] = c;
} else {
logError('Invalid color specified for object "' + n + '", namely "' + o.colors[i] + '".', o.lineNumber + 1);
o.colors[i] = '#ff00ff'; // magenta error color
}
}
if (o.colors.length === 0) {
logError('color not specified for object "' + n + '".', o.lineNumber);
o.colors = ["#ff00ff"];
}
if (o.spritematrix.length === 0) {
o.spritematrix = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
} else {
if (o.spritematrix.length !== 5 || o.spritematrix[0].length !== 5 || o.spritematrix[1].length !== 5 || o.spritematrix[2].length !== 5 || o.spritematrix[3].length !== 5 || o.spritematrix[4].length !== 5) {
logWarning("Sprite graphics must be 5 wide and 5 high exactly.", o.lineNumber);
}
o.spritematrix = generateSpriteMatrix(o.spritematrix);
}
let mask = blankMask.concat([]);
mask[o.layer] = o.id;
glyphDict[n] = mask;
glyphOrder.push([o.lineNumber, n]);
}
let added = true;
while (added) {
added = false;
//then, synonyms
for (let i = 0; i < state.legend_synonyms.length; i++) {
let dat = state.legend_synonyms[i];
let key = dat[0];
let val = dat[1];
if ((!(key in glyphDict) || (glyphDict[key] === undefined)) && (glyphDict[val] !== undefined)) {
added = true;
glyphDict[key] = glyphDict[val];
glyphOrder.push([dat.lineNumber, key]);
}
}
//then, aggregates
for (let i = 0; i < state.legend_aggregates.length; i++) {
let dat = state.legend_aggregates[i];
let key = dat[0];
let vals = dat.slice(1);
let allVallsFound = true;
for (let j = 0; j < vals.length; j++) {
let v = vals[j];
if (glyphDict[v] === undefined) {
allVallsFound = false;
break;
}
}
if ((!(key in glyphDict) || (glyphDict[key] === undefined)) && allVallsFound) {
let mask = blankMask.concat([]);
for (let j = 1; j < dat.length; j++) {
let n = dat[j];
let o = state.objects[n];
if (o === undefined) {
logError('Object not found with name ' + n, state.lineNumber);
}
if (mask[o.layer] === -1) {
mask[o.layer] = o.id;
} else {
if (o.layer === undefined) {
logError('Object "' + n.toUpperCase() + '" has been defined, but not assigned to a layer.', dat.lineNumber);
} else {
let n1 = n.toUpperCase();
let n2 = state.idDict[mask[o.layer]].toUpperCase();
// if (n1 !== n2) {
logError(
'Trying to create an aggregate object (something defined in the LEGEND section using AND) with both "' +
n1 + '" and "' + n2 + '", which are on the same layer and therefore can\'t coexist.',
dat.lineNumber
);
// }
}
}
}
added = true;
glyphDict[dat[0]] = mask;
glyphOrder.push([dat.lineNumber, key]);
}
}
}
//sort glyphs line number
glyphOrder.sort((a, b) => a[0] - b[0]);
glyphOrder = glyphOrder.map(a => a[1]);
state.glyphDict = glyphDict;
state.glyphOrder = glyphOrder;
let aggregatesDict = {};
for (let i = 0; i < state.legend_aggregates.length; i++) {
let entry = state.legend_aggregates[i];
aggregatesDict[entry[0]] = entry.slice(1);
}
state.aggregatesDict = aggregatesDict;
let propertiesDict = {};
for (let i = 0; i < state.legend_properties.length; i++) {
let entry = state.legend_properties[i];
propertiesDict[entry[0]] = entry.slice(1);
}
state.propertiesDict = propertiesDict;
//calculate lookup dictionaries
let synonymsDict = {};
for (let i = 0; i < state.legend_synonyms.length; i++) {
let entry = state.legend_synonyms[i];
let key = entry[0];
let value = entry[1];
if (value in aggregatesDict) {
aggregatesDict[key] = aggregatesDict[value];
} else if (value in propertiesDict) {
propertiesDict[key] = propertiesDict[value];
} else if (key !== value) {
synonymsDict[key] = value;
}
}
state.synonymsDict = synonymsDict;
let modified = true;
while (modified) {
modified = false;
const synonymsDict_keys = Object.keys(synonymsDict);
const synonymsDict_keys_l = synonymsDict_keys.length;
for (let k_i = 0; k_i < synonymsDict_keys_l; k_i++) {
const n = synonymsDict_keys[k_i];
let value = synonymsDict[n];
if (value in propertiesDict) {
delete synonymsDict[n];
propertiesDict[n] = propertiesDict[value];
modified = true;
} else if (value in aggregatesDict) {
delete aggregatesDict[n];
aggregatesDict[n] = aggregatesDict[value];
modified = true;
} else if (value in synonymsDict) {
synonymsDict[n] = synonymsDict[value];
}
}
const propertiesDict_keys = Object.keys(propertiesDict);
const propertiesDict_keys_l = propertiesDict_keys.length;
for (let k_i = 0; k_i < propertiesDict_keys_l; k_i++) {
const n = propertiesDict_keys[k_i];
let values = propertiesDict[n];
for (let i = 0; i < values.length; i++) {
let value = values[i];
if (value in synonymsDict) {
values[i] = synonymsDict[value];
modified = true;
} else if (value in propertiesDict) {
values.splice(i, 1);
let newvalues = propertiesDict[value];
for (let j = 0; j < newvalues.length; j++) {
let newvalue = newvalues[j];
if (values.indexOf(newvalue) === -1) {
values.push(newvalue);
}
}
modified = true;
}
if (value in aggregatesDict) {
logError('Trying to define property "' + n.toUpperCase() + '" in terms of aggregate "' + value.toUpperCase() + '".');
}
}
}
const aggregatesDict_keys = Object.keys(aggregatesDict);
const aggregatesDict_keys_l = aggregatesDict_keys.length;
for (let k_i = 0; k_i < aggregatesDict_keys_l; k_i++) {
const n = aggregatesDict_keys[k_i];
let values = aggregatesDict[n];
for (let i = 0; i < values.length; i++) {
let value = values[i];
if (value in synonymsDict) {
values[i] = synonymsDict[value];
modified = true;
} else if (value in aggregatesDict) {
values.splice(i, 1);
let newvalues = aggregatesDict[value];
for (let j = 0; j < newvalues.length; j++) {
let newvalue = newvalues[j];
if (values.indexOf(newvalue) === -1) {
values.push(newvalue);
}
}
modified = true;
}
if (value in propertiesDict) {
logError('Trying to define aggregate "' + n.toUpperCase() + '" in terms of property "' + value.toUpperCase() + '".');
}
}
}
}
/* determine which properties specify objects all on one layer */
state.propertiesSingleLayer = {};
const propertiesDict_keys = Object.keys(propertiesDict);
const propertiesDict_keys_l = propertiesDict_keys.length;
for (let k_i = 0; k_i < propertiesDict_keys_l; k_i++) {
const key = propertiesDict_keys[k_i];
let values = propertiesDict[key];
let sameLayer = true;
for (let i = 1; i < values.length; i++) {
if ((state.objects[values[i - 1]].layer !== state.objects[values[i]].layer)) {
sameLayer = false;
break;
}
}
if (sameLayer) {
state.propertiesSingleLayer[key] = state.objects[values[0]].layer;
}
}
if (state.idDict[0] === undefined && state.collisionLayers.length > 0) {
logError('You need to have some objects defined');
}
//set default background object
let backgroundid;
let backgroundlayer;
if (state.objects.background === undefined) {
if ('background' in state.synonymsDict) {
let n = state.synonymsDict['background'];
let o = state.objects[n];
backgroundid = o.id;
backgroundlayer = o.layer;
} else if ('background' in state.propertiesDict) {
let backgrounddef = state.propertiesDict['background'];
let n = backgrounddef[0];
let o = state.objects[n];
backgroundid = o.id;
backgroundlayer = o.layer;
for (let i = 1; i < backgrounddef.length; i++) {
let nnew = backgrounddef[i];
let onew = state.objects[nnew];
if (onew.layer !== backgroundlayer) {
let lineNumber = state.original_line_numbers['background'];
logError('Background objects must be on the same layer', lineNumber);
}
}
} else if ('background' in state.aggregatesDict) {
let o = state.objects[state.idDict[0]];
backgroundid = o.id;
backgroundlayer = o.layer;
let lineNumber = state.original_line_numbers['background'];
logError("background cannot be an aggregate (declared with 'and'), it has to be a simple type, or property (declared in terms of others using 'or').", lineNumber);
} else {
//background doesn't exist. Error already printed elsewhere.
let o = state.objects[state.idDict[0]];
if (o != null) {
backgroundid = o.id;
backgroundlayer = o.layer;
}
logError("Seriously, you have to define something to be the background.");
}
} else {
backgroundid = state.objects.background.id;
backgroundlayer = state.objects.background.layer;
}
state.backgroundid = backgroundid;
state.backgroundlayer = backgroundlayer;
}
function levelFromString(state, level) {
let backgroundlayer = state.backgroundlayer;
let backgroundid = state.backgroundid;
let backgroundLayerMask = state.layerMasks[backgroundlayer];
let o = new Level(level[0], level[1].length, level.length - 1, state.collisionLayers.length, null);
o.objects = new Int32Array(o.width * o.height * STRIDE_OBJ);
for (let i = 0; i < o.width; i++) {
for (let j = 0; j < o.height; j++) {
let ch = level[j + 1].charAt(i);
if (ch.length === 0) {
ch = level[j + 1].charAt(level[j + 1].length - 1);
}
let mask = state.glyphDict[ch];
if (mask === undefined) {
if (state.propertiesDict[ch] === undefined) {
logError('Error, symbol "' + ch + '", used in map, not found.', level[0] + j);
} else {
logError('Error, symbol "' + ch + '" is defined using OR, and therefore ambiguous - it cannot be used in a map. Did you mean to define it in terms of AND?', level[0] + j);
}
return o;
}
let maskint = new BitVec(STRIDE_OBJ);
mask = mask.concat([]);
for (let z = 0; z < o.layerCount; z++) {
if (mask[z] >= 0) {
maskint.ibitset(mask[z]);
}
}
for (let w = 0; w < STRIDE_OBJ; ++w) {
o.objects[STRIDE_OBJ * (i * o.height + j) + w] = maskint.data[w];
}
}
}
const levelBackgroundMask = o.calcBackgroundMask(state);
for (let i = 0; i < o.n_tiles; i++) {
let cell = o.getCell(i);
if (!backgroundLayerMask.anyBitsInCommon(cell)) {
cell.ior(levelBackgroundMask);
o.setCell(i, cell);
}
}
return o;
}
//also assigns glyphDict
function levelsToArray(state) {
let levels = state.levels;
let processedLevels = [];
for (let levelIndex = 0; levelIndex < levels.length; levelIndex++) {
let level = levels[levelIndex];
if (level.length === 0) {
continue;
}
if (level[0] === '\n') {
let o = {
message: level[1]
};
splitMessage = wordwrap(o.message, intro_template[0].length);
if (splitMessage.length > 12) {
logWarning('Message too long to fit on screen.', level[2]);
}
processedLevels.push(o);
} else {
let o = levelFromString(state, level);
processedLevels.push(o);
}
}
state.levels = processedLevels;
}
function directionalRule(rule) {
for (let i = 0; i < rule.lhs.length; i++) {
let cellRow = rule.lhs[i];
if (cellRow.length > 1) {
return true;
}
for (let j = 0; j < cellRow.length; j++) {
let cell = cellRow[j];
for (let k = 0; k < cell.length; k += 2) {
if (relativeDirections.indexOf(cell[k]) >= 0) {
return true;
}
}
}
}
for (let i = 0; i < rule.rhs.length; i++) {
let cellRow = rule.rhs[i];
for (let j = 0; j < cellRow.length; j++) {
let cell = cellRow[j];
for (let k = 0; k < cell.length; k += 2) {
if (relativeDirections.indexOf(cell[k]) >= 0) {
return true;
}
}
}
}
return false;
}
function findIndexAfterToken(str, tokens, tokenIndex) {
str = str.toLowerCase();
let curIndex = 0;
for (let i = 0; i <= tokenIndex; i++) {
let token = tokens[i];
curIndex = str.indexOf(token, curIndex) + token.length;
}
return curIndex;
}
function rightBracketToRightOf(tokens, i) {
for (; i < tokens.length; i++) {
if (tokens[i] === "]") {
return true;
}
}
return false;
}
function processRuleString(rule, state, curRules) {
/*
intermediate structure
dirs: Directions[]
pre : CellMask[]
post : CellMask[]
//pre/post pairs must have same lengths
final rule structure
dir: Direction
pre : CellMask[]
post : CellMask[]
*/
let line = rule[0];
let lineNumber = rule[1];
let origLine = rule[2];
// STEP ONE, TOKENIZE
line = line.replace(/\[/g, ' [ ').replace(/\]/g, ' ] ').replace(/\|/g, ' | ').replace(/\-\>/g, ' -> ');
line = line.trim();
if (line[0] === '+') {
line = line.substring(0, 1) + " " + line.substring(1, line.length);
}
let tokens = line.split(/\s/).filter(function (v) { return v !== '' });
if (tokens.length === 0) {
logError('Spooky error! Empty line passed to rule function.', lineNumber);
}
// STEP TWO, READ DIRECTIONS
/*
STATE
0 - scanning for initial directions
LHS
1 - reading cell contents LHS
2 - reading cell contents RHS
*/
let parsestate = 0;
let directions = [];
let curcell = null; // [up, cat, down mouse]
let curcellrow = []; // [ [up, cat] [ down, mouse ] ]
let incellrow = false;
let appendGroup = false;
let rhs = false;
let lhs_cells = [];
let rhs_cells = [];
let late = false;
let rigid = false;
let groupNumber = lineNumber;
let commands = [];
let randomRule = false;
let has_plus = false;
if (tokens.length === 1) {
if (tokens[0] === "startloop") {
let rule_line = {
bracket: 1
}
return rule_line;
} else if (tokens[0] === "endloop") {
let rule_line = {
bracket: -1
}
return rule_line;
}
}
if (tokens.indexOf('->') === -1) {
logError("A rule has to have an arrow in it. There's no arrow here! Consider reading up about rules - you're clearly doing something weird", lineNumber);
}
curcell = [];
let bracketbalance = 0;
for (let i = 0; i < tokens.length; i++) {
let token = tokens[i];
switch (parsestate) {
case 0:
{
//read initial directions
if (token === '+') {
has_plus = true;
if (groupNumber === lineNumber) {
if (curRules.length === 0) {
logError('The "+" symbol, for joining a rule with the group of the previous rule, needs a previous rule to be applied to.', lineNumber);
has_plus = false;
}
if (i !== 0) {
logError('The "+" symbol, for joining a rule with the group of the previous rule, must be the first symbol on the line ', lineNumber);
}
if (has_plus) {
groupNumber = curRules[curRules.length - 1].groupNumber;
}
} else {
logError('Two "+"s (the "append to previous rule group" symbol) applied to the same rule.', lineNumber);
}
} else if (token in directionaggregates) {
directions = directions.concat(directionaggregates[token]);
} else if (token === 'late') {
late = true;
} else if (token === 'rigid') {
rigid = true;
} else if (token === 'random') {
randomRule = true;
if (has_plus) {
logError(`A rule-group can only be marked random by the opening rule in the group (aka, a '+' and 'random' can't appear as rule modifiers on the same line). Why? Well, you see "random" isn't a property of individual rules, but of whole rule groups. It indicates that a single possible application of some rule from the whole group should be applied at random.`, lineNumber)
}
} else if (simpleAbsoluteDirections.indexOf(token) >= 0) {
directions.push(token);
} else if (simpleRelativeDirections.indexOf(token) >= 0) {
logError('You cannot use relative directions (\"^v<>\") to indicate in which direction(s) a rule applies. Use absolute directions indicators (Up, Down, Left, Right, Horizontal, or Vertical, for instance), or, if you want the rule to apply in all four directions, do not specify directions', lineNumber);
} else if (token === '[') {
if (directions.length === 0) {
directions = directions.concat(directionaggregates['orthogonal']);
}
parsestate = 1;
i--;
} else {
logError("The start of a rule must consist of some number of directions (possibly 0), before the first bracket, specifying in what directions to look (with no direction specified, it applies in all four directions). It seems you've just entered \"" + token.toUpperCase() + '\".', lineNumber);
}
break;
}
case 1:
{
if (token === '[') {
bracketbalance++;
if (bracketbalance > 1) {
logWarning("Multiple opening brackets without closing brackets. Something fishy here. Every '[' has to be closed by a ']', and you can't nest them.", lineNumber);
}
if (curcell.length > 0) {
logError('Error, malformed cell rule - encountered a "["" before previous bracket was closed', lineNumber);
}
incellrow = true;
curcell = [];
} else if (reg_directions_only.exec(token)) {
if (curcell.length % 2 === 1) {
logError("Error, an item can only have one direction/action at a time, but you're looking for several at once!", lineNumber);
} else if (!incellrow) {
logWarning("Invalid syntax. Directions should be placed at the start of a rule.", lineNumber);
} else if (late && token !== 'no' && token !== 'random' && token !== 'randomdir') {
logError("Movements cannot appear in late rules.", lineNumber);
} else {
curcell.push(token);
}
} else if (token === '|') {
if (!incellrow) {
logWarning('Janky syntax. "|" should only be used inside cell rows (the square brackety bits).', lineNumber);
} else if (curcell.length % 2 === 1) {
logError('In a rule, if you specify a movement, it has to act on an object.', lineNumber);
} else {
curcellrow.push(curcell);
curcell = [];
}
} else if (token === ']') {
bracketbalance--;
if (bracketbalance < 0) {
logWarning("Multiple closing brackets without corresponding opening brackets. Something fishy here. Every '[' has to be closed by a ']', and you can't nest them.", lineNumber);
return null;
}
if (curcell.length % 2 === 1) {
if (curcell[0] === '...') {
logError('Cannot end a rule with ellipses.', lineNumber);
} else {
logError('In a rule, if you specify a movement, it has to act on an object.', lineNumber);
}
} else {
curcellrow.push(curcell);
curcell = [];
}
if (rhs) {
rhs_cells.push(curcellrow);
} else {
lhs_cells.push(curcellrow);
}
curcellrow = [];
incellrow = false;
} else if (token === '->') {
if (groupNumber !== lineNumber) {
let parentrule = curRules[curRules.length - 1];
if (parentrule.late !== late) {
logWarning('Oh gosh you can mix late and non-late rules in a rule-group if you really want to, but gosh why would you want to do that? What do you expect to accomplish?', lineNumber);
}
}
if (incellrow) {
logWarning('Encountered an unexpected "->" inside square brackets. It\'s used to separate states, it has no place inside them >:| .', lineNumber);
} else if (rhs) {
logError('Error, you can only use "->" once in a rule; it\'s used to separate before and after states.', lineNumber);
return null;
} else {
rhs = true;
}
} else if (state.names.indexOf(token) >= 0) {
if (!incellrow) {
logWarning("Invalid token " + token.toUpperCase() + ". Object names should only be used within cells (square brackets).", lineNumber);
} else {
//check that the object is not already present in the cell
for (let j = 0; j < curcell.length; j += 2) {
if (curcell[j + 1] === token) {
logError(`You cannot specify the same object more than once in a single cell (in this case ${token} occurs mutliple times).`, lineNumber);
if (token in state.propertiesDict){
logWarningNoLine(`( However, noticing that you're committing this crime with <i>properties</i>, and not being able to help but acknowledge that you <i>may</i> be trying to do something esoteric and <i>clever</i> with the property inference system, I might be brought to suggest that you consider this: you can have multiple equivalent properties with different names. )`);
}
}
}
if (curcell.length % 2 === 0) {
curcell.push('');
curcell.push(token);
} else if (curcell.length % 2 === 1) {
curcell.push(token);
}
}
} else if (token === '...') {
if (!incellrow) {
logWarning("Invalid syntax, ellipses should only be used within cells (square brackets).", lineNumber);
} else {
curcell.push(token);
curcell.push(token);
}
} else if (commandwords.indexOf(token) >= 0) {
if (rhs === false) {
logError("Commands should only appear at the end of rules, not in or before the pattern-detection/-replacement sections.", lineNumber);
} else if (incellrow || rightBracketToRightOf(tokens, i)) {//only a warning for legacy support reasons.
logWarning("Commands should only appear at the end of rules, not in or before the pattern-detection/-replacement sections.", lineNumber);
}
if (token === 'message') {
let messageIndex = findIndexAfterToken(origLine, tokens, i);
let messageStr = origLine.substring(messageIndex).trim();
if (messageStr === "") {
messageStr = " ";
//needs to be nonempty or the system gets confused and thinks it's a whole level message rather than an interstitial.
}
commands.push([token, messageStr]);
i = tokens.length;
} else {
if (commandwords_sfx.indexOf(token) >= 0) {
//check defined
let found = false;
for (let j = 0; j < state.sounds.length; j++) {
let sound = state.sounds[j];
if (sound[0][0] === token) {
found = true;
}
}
if (!found) {
logWarning('Sound effect "' + token + '" not defined.', lineNumber);
}
}
commands.push([token]);
}
} else {
logError('Error, malformed cell rule - was looking for cell contents, but found "' + token + '". What am I supposed to do with this, eh, please tell me that.', lineNumber);
}
}
}
}
if (late && rigid) {
logError("Late rules cannot be marked as rigid (rigid rules are all about dealing with the consequences of unresolvable movements, and late rules can't even have movements).", lineNumber);
}
if (lhs_cells.length != rhs_cells.length) {
if (commands.length > 0 && rhs_cells.length === 0) {
//ok
} else {
logWarning('Error, when specifying a rule, the number of matches (square bracketed bits) on the left hand side of the arrow must equal the number on the right', lineNumber);
}
} else {
for (let i = 0; i < lhs_cells.length; i++) {
if (lhs_cells[i].length != rhs_cells[i].length) {
logError('In a rule, each pattern to match on the left must have a corresponding pattern on the right of equal length (number of cells).', lineNumber);
state.invalid = true;
}
if (lhs_cells[i].length === 0) {
logError("You have an totally empty pattern on the left-hand side. This will match *everything*. You certainly don't want this.");
}
}
}
if (lhs_cells.length === 0) {
logError('This rule refers to nothing. What the heck? :O', lineNumber);
}
let rule_line = {
directions: directions,
lhs: lhs_cells,
rhs: rhs_cells,
lineNumber: lineNumber,
late: late,
rigid: rigid,
groupNumber: groupNumber,
commands: commands,
randomRule: randomRule
};
if (directionalRule(rule_line) === false && rule_line.directions.length > 1) {
rule_line.directions.splice(1);
}
//next up - replace relative directions with absolute direction
return rule_line;
}
function deepCloneHS(HS) {
let cloneHS = HS.map(function (arr) { return arr.map(function (deepArr) { return deepArr.slice(); }); });
return cloneHS;
}
function deepCloneRule(rule) {
let clonedRule = {
direction: rule.direction,
lhs: deepCloneHS(rule.lhs),
rhs: deepCloneHS(rule.rhs),
lineNumber: rule.lineNumber,
late: rule.late,
rigid: rule.rigid,
groupNumber: rule.groupNumber,
commands: rule.commands,
randomRule: rule.randomRule
};
return clonedRule;
}
function checkSuperfluousCoincidences(state,rules){
/*
First, let's check for 'X no X' on the RHS.
*/
// check that that we don't have an object on one layer required, and at the same time
// 'no X' where x is also on that layer - it's "no wall" and player in the same cell - for then "no wall" is
// superfluous.
// for each rule
//first, find a list of layers where we *know* something has to be
let required_layers = new BitVec(Math.ceil(LAYER_COUNT/32)|0);
let required_objects = new BitVec(STRIDE_OBJ);
const rules_l = rules.length;
for (let i=0;i<rules_l;i++){
let rule = rules[i];
// First do a RHS check - you shouldn't have something amounting to
// X no X on the RHS. (even if the engine does it internally a lot later)
const rhs_len = rule.rhs.length;
for (let j=0;j<rhs_len;j++){
let rhs_group = rule.rhs[j];
const rhs_group_len = rhs_group.length;
for (let k=0;k<rhs_group_len;k++){
let cell = rhs_group[k];
var objects_present = [];
var objects_present_mask = new BitVec(STRIDE_OBJ);
for (let l=0;l<cell.length;l+=2){
let item = cell[l];
if (!item.startsWith("no")){
let no_name = cell[l+1];
if (state.objects.hasOwnProperty(no_name)){
objects_present.push(no_name);
objects_present_mask.ibitset(state.objects[no_name].id);
} else if (state.propertiesSingleLayer.hasOwnProperty(no_name)){
// objects_present.push(no_name);
// let property_obs = state.propertiesDict[no_name];
// for (let m=0;m<property_obs.length;m++){
// let ob_data = state.objects[property_obs[m]];
// objects_present_mask.ibitset(ob_data.id);
// }
} else if (state.propertiesDict.hasOwnProperty(no_name)){
// this is more complicated a case, right?
// let property_obs = state.propertiesDict[no_name];
// for (let m=0;m<property_obs.length;m++){
// let ob_data = state.objects[property_obs[m]];
// objects_present_mask.ibitset(ob_data.id);
// }
}
}
}
//for each 'no' object
for (let l=0;l<cell.length;l+=2){
let item = cell[l];
if (item.startsWith("no")){
let no_name = cell[l+1];
var no_name_mask = state.objectMasks[no_name];
//if no_name overlaps with any objects_present, then we have a problem.
if (no_name_mask.anyBitsInCommon(objects_present_mask)){
logError(`You have specified that there should be NO ${no_name.toUpperCase()} but there is also a requirement that ${objects_present.join(", ").toUpperCase()} be here. This is a mistake right?`, rule.lineNumber);
}
}
}
}
}
//secondly, for all 'no X' on the LHS, can remove any corresponding verbatim 'no X' on the RHS.
for (let j=0;j<rhs_len;j++){
let rhs_group = rule.rhs[j];
const rhs_group_len = rhs_group.length;
for (let k=0;k<rhs_group_len;k++){
let cell = rhs_group[k];
for (let l=0;l<cell.length;l+=2){
let item = cell[l];
if (item.startsWith("no")){
let no_name = cell[l+1];
//look for a 'no X' on the LHS in the same position
const lhs_cell = rule.lhs[j][k];
for (let m=0;m<lhs_cell.length;m+=2){
if (lhs_cell[m].startsWith("no") && lhs_cell[m+1] === no_name){
//we have a match - remove the 'no X' from the LHS
cell.splice(l,2);
break;
}
}
}
}
}
}
// thirdly, trim unnecessary 'no X's on the LHS - e.g. [ player no wall ]
const lhs_len = rule.lhs.length;
for (let j=0;j<lhs_len;j++){
let lhs_group = rule.lhs[j];
const lhs_group_len = lhs_group.length;
for (let k=0;k<lhs_group_len;k++){
let cell = lhs_group[k];
// cell is an array of pairs - it looks like:
// ["", "player", "no", "wall", "", "target"]
required_layers.setZero();
required_objects.setZero();
let occupier={};
for (let l=0;l<cell.length;l+=2){
let entity_modifier = cell[l];
if (entity_modifier==="no"){
continue;
}
let entity_name = cell[l+1]
let layer=[];
//if it's a single-layer property
if (state.propertiesSingleLayer.hasOwnProperty(entity_name)){
let layer = state.propertiesSingleLayer[entity_name];
required_layers.ibitset(layer);
let property_obs = state.propertiesDict[entity_name];
const property_obs_len = property_obs.length;
for (let m=0;m<property_obs_len;m++){
const object_name = property_obs[m];
const object_data = state.objects[object_name];
required_objects.ibitset(object_data.id);
}
occupier[layer]=entity_name;
} else if (state.objects.hasOwnProperty(entity_name)){