forked from jmoenig/Snap
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ypr.js
1444 lines (1386 loc) · 48 KB
/
ypr.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
/*
Copyright 2012 Nathan Dinsmore
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Last changed 2013-04-03 by Jens Moenig (disabled text area overlay)
*/
var sb = (function (sb) {
'use strict';
function extend(o, p) {
var key;
for (key in p) if (p.hasOwnProperty(key)) {
o[key] = p[key];
}
}
sb.$extend = extend;
extend((sb.Ref = function (id) {
this.id = id;
}).prototype, {
isRef: true
});
extend((sb.Dictionary = function (keys, values) {
this.keys = keys;
this.values = values;
}).prototype, {
get: function (key) {
return this.values[this.keys.indexOf(key)];
},
set: function (key, value) {
var i = this.keys.indexOf(key);
if (i === -1) {
this.keys.push(key);
this.values.push(value);
} else {
this.values[i] = value;
}
}
});
sb.Color = function (rgb, a) {
this.r = (rgb / 0x100000 | 0) % 0x400 / (0x400 - 1);
this.g = (rgb / 0x400 | 0) % 0x400 / (0x400 - 1);
this.b = (rgb % 0x400) / (0x400 - 1);
this.a = a / (0x100 - 1);
};
sb.Point = function (x, y) {
this.x = x;
this.y = y;
};
sb.Rectangle = function (x, y, x2, y2) {
this.origin = new sb.Point(x, y);
this.corner = new sb.Point(x2, y2);
};
sb.indexedColors = [
[1, 1, 1, 1],
[0, 0, 0, 1],
[1, 1, 1, 1],
[.5, .5, .5, 1],
[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 1],
[1, 1, 0, 1],
[1, 0, 1, 1],
[.125, .125, .125, 1],
[.25, .25, .25, 1],
[.375, .375, .375, 1],
[.625, .625, .625, 1],
[.75, .75, .75, 1],
[.875, .875, .875, 1]
];
(function () {
var i, r, g, b, grayVal;
for (i = 1; i <= 31; ++i) {
if (i % 4 != 0) {
grayVal = i / 32;
sb.indexedColors[i + 15] = [grayVal, grayVal, grayVal, 1];
}
}
for (r = 0; r < 6; ++r) {
for (g = 0; g < 6; ++g) {
for (b = 0; b < 6; ++b) {
i = 40 + 36 * r + 6 * b + g;
sb.indexedColors[i] = [r / 5, g / 5, b / 5, 1];
}
}
}
})();
sb.colorDepthLengths = {
1: 1,
2: 2,
4: 4,
8: 8,
15: 5,
16: 5,
12: 4,
9: 3
};
extend((sb.ColorStream = function (bitmap, depth) {
var i = 0,
l = bitmap.length,
b = this.bits = [],
n;
this.length = sb.colorDepthLengths[this.depth = depth];
this.position = 0;
while (i < l) {
n = bitmap[i++];
b.push(n / 0x80 & 1);
b.push(n / 0x40 & 1);
b.push(n / 0x20 & 1);
b.push(n / 0x10 & 1);
b.push(n / 0x8 & 1);
b.push(n / 0x4 & 1);
b.push(n / 0x2 & 1);
b.push(n & 1);
}
}).prototype, {
read: function () {
var i = this.length,
b = this.bits,
n = 0;
while (i--) {
n = n * 2 + b[this.position++];
}
return n;
}
});
extend((sb.ColorStreamIndexed = function (bitmap, depth) {
sb.ColorStream.call(this, bitmap, depth);
}).prototype = Object.create(sb.ColorStream.prototype), {
next: function (b) {
var c = sb.indexedColors[this.read()];
if (!c) return c;
b[0] = c[0];
b[1] = c[1];
b[2] = c[2];
b[3] = c[3];
}
});
extend((sb.ColorStreamRGB = function (bitmap, depth) {
sb.ColorStream.call(this, bitmap, depth);
this.max = Math.pow(2, this.length) - 1;
}).prototype = Object.create(sb.ColorStream.prototype), {
next: function (b) {
var c;
switch (this.depth) {
case 16:
++this.position;
c = [this.read() / this.max, this.read() / this.max, this.read() / this.max, 1];
if (c[0] + c[1] + c[2] === 0) {
return b[0] = b[1] = b[2] = b[3] = 0;
}
b[0] = c[0];
b[1] = c[1];
b[2] = c[2];
b[3] = c[3];
return;
case 12:
this.position += 3;
break;
}
b[0] = this.read() / this.max;
b[1] = this.read() / this.max;
b[2] = this.read() / this.max;
b[3] = 1;
}
});
extend((sb.ColorStream32 = function (bitmap, depth) {
this.bytes = bitmap;
if (depth === 32) {
this.next = this.nextAlpha;
}
this.position = 0;
}).prototype, {
next: function (b) {
b[0] = this.read() / 255;
b[1] = this.read() / 255;
b[2] = this.read() / 255;
b[3] = 1;
},
nextAlpha: function (b) {
var a = this.read() / 255;
b[0] = this.read() / 255;
b[1] = this.read() / 255;
b[2] = this.read() / 255
b[3] = a;
},
read: function () {
return this.bytes[this.position++];
}
});
sb.colorStreams = {
1: sb.ColorStreamIndexed,
2: sb.ColorStreamIndexed,
4: sb.ColorStreamIndexed,
8: sb.ColorStreamIndexed,
15: sb.ColorStreamRGB,
16: sb.ColorStreamRGB,
32: sb.ColorStream32,
24: sb.ColorStream32,
12: sb.ColorStreamRGB,
9: sb.ColorStreamRGB
};
sb.getColorStream = function (bitmap, depth) {
return new sb.colorStreams[depth](bitmap, depth);
};
extend((sb.Form = function (w, h, d, o, b) {
this.width = w;
this.height = h;
this.depth = d;
this.offset = o;
this.bits = b;
}).prototype, {
init: function (bm) {
if (this.bits.isBitmap) {
this.bitmap = this.bits;
} else {
this.decompress(bm);
}
this.image = document.createElement('canvas');
this.image.width = this.width;
this.image.height = this.height;
},
decompress: function (bm) {
var b = this.bits,
p = 0,
q = 0,
r = !!bm,
length = (i = b[p++], i <= 223 ? i : i < 255 ? (i - 224) * 256 + b[p++] : (b[p++] << 24) + (b[p++] << 16) + (b[p++] << 8) + b[p++]),
bm, i, n, d, e, f, g;
// stream = new sb.Reader().on(this.bits),
this.bitmap = bm || (bm = []);
while (p < b.length) {
i = b[p++];
if (i > 223) {
i = i < 255 ? (i - 224) * 256 + b[p++] : (b[p++] << 24) + (b[p++] << 16) + (b[p++] << 8) + b[p++];
}
n = i >> 2;
switch (i & 3) {
case 1:
d = b[p++];
n *= 4;
while (n--) {
bm[q++] = d;
}
break;
case 2:
// d = stream.readBytes(4);
d = b[p++];
e = b[p++];
f = b[p++];
g = b[p++];
while (n--) {
if (r) {
bm[q++] = e;
bm[q++] = f;
bm[q++] = g;
bm[q++] = d;
} else {
bm[q++] = d;
bm[q++] = e;
bm[q++] = f;
bm[q++] = g;
}
}
break;
case 3:
while (n--) {
if (r) {
d = b[p++];
bm[q++] = b[p++];
bm[q++] = b[p++];
bm[q++] = b[p++];
bm[q++] = d;
} else {
bm[q++] = b[p++];
bm[q++] = b[p++];
bm[q++] = b[p++];
bm[q++] = b[p++];
}
}
// bm.push.apply(bm, stream.readBytes(n * 4));
break;
}
}
},
load: function () {
var w = this.width,
h = this.height,
x, y, i, imageData, data, context, colors, color, b;
if (this.depth === 32) {
this.image = document.createElement('canvas');
this.image.width = this.width;
this.image.height = this.height;
data = (imageData = (context = this.image.getContext('2d')).createImageData(this.width, this.height)).data;
this.decompress(data);
context.putImageData(imageData, 0, 0);
return;
}
color = [0, 0, 0, 0];
if (this.depth === 16) {
w = this.width += 1;
}
this.init();
colors = sb.getColorStream(this.bitmap, this.depth);
data = (imageData = (context = this.image.getContext('2d')).createImageData(this.width, this.height)).data;
for (x = 0; x < w; ++x) {
for (y = 0; y < h; ++y) {
colors.next(color);
if (!color) continue;
i = (x * h + y) * 4;
data[i] = color[0] * 255;
data[i + 1] = color[1] * 255;
data[i + 2] = color[2] * 255;
data[i + 3] = color[3] * 255;
}
}
context.putImageData(imageData, 0, 0);
}
});
extend((sb.ColorForm = function (w, h, d, o, b, c) {
this.width = w;
this.height = h;
this.depth = d;
this.offset = o;
this.bits = b;
this.colors = c;
}).prototype = Object.create(sb.Form.prototype), {
load: function () {
var w = this.width,
h = this.height,
colors = this.colors,
bits, x, y, i, imageData, data, context, color;
this.init();
data = (imageData = (context = this.image.getContext('2d')).createImageData(this.width, this.height)).data;
bits = this.bitmap;
for (x = 0; x < w; ++x) {
for (y = 0; y < h; ++y) {
color = colors[bits[x * h + y]];
if (!color) continue;
i = (x * h + y) * 4;
data[i] = color.r * 255;
data[i + 1] = color.g * 255;
data[i + 2] = color.b * 255;
data[i + 3] = color.a * 255;
}
}
context.putImageData(imageData, 0, 0);
}
});
sb.fields = {};
sb.classIDs = {};
sb.classNames = {};
sb.addFields = function (id, name, base, fields) {
sb.classIDs[name] = id;
sb.classNames[id] = name;
fields = fields.length ? fields.split(',') : [];
if (base) {
base = sb.fields[sb.classIDs[base]];
if (!base) throw new Error('Initialization error');
fields = base.concat(fields);
}
sb.fields[id] = fields;
};
sb.addFields(100, 'Morph', '', 'bounds,owner,submorphs,color,flags,properties');
sb.addFields(101, 'BorderedMorph', 'Morph', 'borderWidth,borderColor');
sb.addFields(102, 'RectangleMorph', 'BorderedMorph', '');
sb.addFields(103, 'EllipseMorph', 'BorderedMorph', '');
sb.addFields(104, 'AlignmentMorph', 'RectangleMorph', 'orientation,centering,hResizing,vResizing,inset');
sb.addFields(105, 'StringMorph', 'Morph', 'fontSpec,emphasis,contents');
sb.addFields(-1, 'Slider', 'BorderedMorph', 'slider,value,setValueSelector,sliderShadow,sliderColor,descending,model');
sb.addFields(-2, 'AbstractSound', '', '');
sb.addFields(-3, 'ScriptableScratchMorph', 'Morph', 'objName,vars,blocksBin,customBlocks,isClone,media,costume');
sb.addFields(-4, 'ArgMorph', 'BorderedMorph', 'labelMorph');
sb.addFields(-5, 'PasteUpMorph', 'BorderedMorph', '');
sb.addFields(-6, 'ScratchMedia', '', 'mediaName');
sb.addFields(-7, 'ScrollFrameMorph', 'BorderedMorph', '');
sb.addFields(106, 'UpdatingStringMorph', 'StringMorph', 'format,target,getSelector,putSelector,parameter,floatPrecision,growable,stepTime');
sb.addFields(107, 'SimpleSliderMorph', 'Slider', 'target,arguments,minVal,maxVal,truncate,sliderThickness');
sb.addFields(108, 'SimpleButtonMorph', 'RectangleMorph', 'target,actionSelector,arguments,actWhen');
sb.addFields(109, 'SampledSound', 'AbstractSound', 'envelopes,scaledVol,initialCount,samples,originalSamplingRate,samplesSize,scaledIncrement,scaledInitialIndex');
sb.addFields(110, 'ImageMorph', 'Morph', 'form,transparency');
sb.addFields(111, 'SketchMorph', 'Morph', 'originalForm,rotationCenter,rotationDegrees,rotationStyle,scalePoint,offsetWhenRotated');
sb.addFields(123, 'SensorBoardMorph', 'Morph', 'portNum');
sb.addFields(124, 'ScratchSpriteMorph', 'ScriptableScratchMorph', 'visibility,scalePoint,rotationDegrees,rotationStyle,volume,tempoBPM,draggable,sceneStates,lists,virtualScale,ownerSprite,subsprites,rotateWithOwner,refPos,prototype,deletedAttributes');
sb.addFields(125, 'ScratchStageMorph', 'ScriptableScratchMorph', 'zoom,hPan,vPan,obsoleteSavedState,sprites,volume,tempoBPM,sceneStates,lists');
sb.addFields(140, 'ChoiceArgMorph', 'ArgMorph', 'isBoolean,options,choice,getOptionsSelector');
sb.addFields(141, 'ColorArgMorph', 'ArgMorph', '');
sb.addFields(142, 'ExpressionArgMorph', 'ArgMorph', 'isNumber');
sb.addFields(145, 'SpriteArgMorph', 'ArgMorph', 'morph');
sb.addFields(147, 'BlockMorph', 'Morph', 'isSpecialForm,oldColor');
sb.addFields(148, 'CommandBlockMorph', 'BlockMorph', 'commandSpec,argMorphs,titleMorph,receiver,selector,isReporter,isTimed,wantsName,wantsPossession');
sb.addFields(149, 'CBlockMorph', 'CommandBlockMorph', 'nestedBlock,nextBlock');
sb.addFields(151, 'HatBlockMorph', 'CommandBlockMorph', 'scriptNameMorph,indicatorMorph,scriptOwner,parameters,isClickable');
sb.addFields(153, 'ScratchScriptsMorph', 'PasteUpMorph', '');
sb.addFields(154, 'ScratchSliderMorph', 'AlignmentMorph', 'slider,sliderMin,sliderMax,variable');
sb.addFields(155, 'WatcherMorph', 'AlignmentMorph', 'titleMorph,readout,readoutFrame,scratchSlider,watcher,isSpriteSpecific,unused,sliderMin,sliderMax,isLarge');
sb.addFields(157, 'SetterBlockMorph', 'CommandBlockMorph', 'variable');
sb.addFields(158, 'EventHatMorph', 'HatBlockMorph', '');
sb.addFields(170, 'ReporterBlockMorph', 'CommandBlockMorph', 'isBoolean');
sb.addFields(160, 'VariableBlockMorph', 'ReporterBlockMorph', '');
sb.addFields(162, 'ImageMedia', 'ScratchMedia', 'form,rotationCenter,textBox,jpegBytes,compositeForm');
sb.addFields(163, 'MovieMedia', 'ScratchMedia', 'fileName,fade,fadeColor,zoom,hPan,vPan,msecsPerFrame,currentFrame,moviePlaying');
sb.addFields(164, 'SoundMedia', 'ScratchMedia', 'originalSound,volume,balance,compressedSampleRate,compressedBitsPerSample,compressedData');
sb.addFields(165, 'KeyEventHatMorph', 'HatBlockMorph', '');
sb.addFields(166, 'BooleanArgMorph', 'ArgMorph', '');
sb.addFields(167, 'EventTitleMorph', 'ArgMorph', '');
sb.addFields(168, 'MouseClickEventHatMorph', 'HatBlockMorph', '');
sb.addFields(169, 'ExpressionArgMorphWithMenu', 'ExpressionArgMorph', 'menuMorph,getMenuSelector,specialValue');
sb.addFields(171, 'MultilineStringMorph', 'BorderedMorph', 'fontSpec,textColor,selectionColor,lines');
sb.addFields(172, 'ToggleButton', 'SimpleButtonMorph', 'onForm,offForm,overForm,disabledForm,isMomentary,toggleMode,isOn,isDisabled');
sb.addFields(173, 'WatcherReadoutFrameMorph', 'BorderedMorph', '');
sb.addFields(174, 'WatcherSliderMorph', 'SimpleSliderMorph', '');
sb.addFields(175, 'ScratchListMorph', 'BorderedMorph', 'listName,strings,target,complex');
sb.addFields(176, 'ScrollingStringMorph', 'BorderedMorph', 'fontSpec,showScrollbar,firstVisibleLine,textColor,selectionColor,lines');
sb.addFields(180, 'ScrollFrameMorph2', 'ScrollFrameMorph', '');
sb.addFields(181, 'ListMultilineStringMorph', 'MultilineStringMorph', '');
sb.addFields(182, 'ScratchScrollBar', 'Morph', '');
sb.addFields(200, 'CustomCommandBlockMorph', 'CommandBlockMorph', 'userSpec');
sb.addFields(201, 'CustomBlockDefinition', '', 'userSpec,blockVars,isAtomic,isReporter,isBoolean,body,answer,type,category,declarations,defaults,isGlobal');
sb.addFields(203, 'ReporterScriptBlockMorph', 'ReporterBlockMorph', '');
sb.addFields(202, 'CommandScriptBlockMorph', 'ReporterScriptBlockMorph', '');
sb.addFields(205, 'VariableFrame', '', 'vars');
sb.addFields(206, 'CustomReporterBlockMorph', 'ReporterBlockMorph', 'userSpec');
sb.addFields(207, 'CReporterSlotMorph', 'ReporterScriptBlockMorph', '');
sb.addFields(300, 'StringFieldMorph', 'BorderedMorph', '');
sb.addFields(301, 'MultiArgReporterBlockMorph', 'ReporterBlockMorph', '');
(function (C, p) {
p.on = function (bytes) {
this.bytes = bytes;
if (!bytes.subarray) bytes.subarray = bytes.slice;
this.position = 0;
return this;
};
p.readYPR = function (bytes) {
var version, infoSize, info, stage;
console.time('readSB');
this.on(bytes);
// skip header
this.matchBytes([66, 108, 111, 120, 69, 120, 112, 86]);
version = +(String.fromCharCode(this.next()) + String.fromCharCode(this.next()));
if (version < 1) {
throw new Error('Invalid version');
}
// read info
infoSize = this.uint32();
info = this.read();
this.position = infoSize + 14; // header + uint32
stage = this.read();
this.onload({
reader: this,
info: info,
stage: stage
});
console.timeEnd('readSB');
};
p.readInfo = function (bytes) {
var version, infoSize, info;
this.on(bytes);
this.matchBytes([66, 108, 111, 120, 69, 120, 112, 86]);
version = +(String.fromCharCode(this.next()) + String.fromCharCode(this.next()));
if (version < 1) {
throw new Error('Invalid version');
}
// read info
infoSize = this.uint32();
info = this.read();
this.onload({
reader: this,
info: info
});
};
p.read = function () {
var i, objectCount;
this.objects = [];
this.readHeader();
objectCount = this.uint32();
i = objectCount;
while (i--) {
this.objects.push(this.readObject());
}
i = objectCount;
while (i--) {
this.fixReferences(this.objects[i]);
}
return this.objects[0][1];
};
p.fixReferences = function (object) {
var classID = object[0],
value = object[1],
i = 0,
fields, source;
if (classID < 99) {
this.fixFixedFormat(classID, value);
} else {
this.fixArray(object[3]);
fields = sb.fields[classID];
if (!fields)
throw new Error('Invalid class ID ' + classID);
source = value.fields;
delete value.fields;
value.className = sb.classNames[classID];
i = fields.length;
while (i--) {
value[fields[i]] = source[i];
}
}
};
p.fixArray = function (a) {
var i = a.length,
o;
while (i--) {
if ((o = a[i]) && o.isRef) {
if (o.id > this.objects.length) {
throw new Error('Invalid object reference');
}
a[i] = this.objects[o.id - 1][1];
}
}
};
p.targetObjectFor = function (o) {
if (o && o.isRef) {
if (o.id > this.objects.length)
throw new Error('Invalid object reference');
return this.objects[o.id - 1][1];
}
return o;
};
p.fixFixedFormat = function (classID, object) {
switch (classID) {
case 20: // Array
case 21: // OrderedCollection
case 22: // Set
case 23: // IdentitySet
this.fixArray(object);
return object;
case 24: // Dictionary
case 25: // IdentityDictionary
this.fixArray(object.keys);
this.fixArray(object.values);
break;
case 32: // Point
object.x = this.targetObjectFor(object.x);
object.y = this.targetObjectFor(object.y);
break;
case 33: // Rectangle
object.origin.x = this.targetObjectFor(object.origin.x);
object.origin.y = this.targetObjectFor(object.origin.y);
object.corner.x = this.targetObjectFor(object.corner.x);
object.corner.y = this.targetObjectFor(object.corner.y);
break;
case 34: // Form
object.offset = this.targetObjectFor(object.offset);
object.bits = this.targetObjectFor(object.bits);
object.load();
break;
case 35: // ColorForm
object.offset = this.targetObjectFor(object.offset);
object.bits = this.targetObjectFor(object.bits);
object.colors = this.targetObjectFor(object.colors);
object.load();
break;
}
return object;
};
p.readObject = function () {
var classID = this.next(),
version, fieldCount, fields;
if (classID > 99) {
version = this.next();
fieldCount = this.next();
fields = [];
while (fieldCount--) {
fields.push(this.readField());
}
return [classID, { fields: fields }, version, fields];
}
return [classID, this.readFixedFormat(classID)];
};
p.readField = function () {
var classID = this.next();
if (classID === 99) {
return new sb.Ref(this.uint24());
}
return this.readFixedFormat(classID);
};
p.readFixedFormat = function (classID) {
var a, n;
switch (classID) {
case 1: // UndefinedObject
return null;
case 2: // True
return true;
case 3: // False
return false;
case 4: // SmallInteger
return this.int32();
case 5: // SmallInteger16
return this.int16();
case 6: // LargePositiveInteger
case 7: // LargeNegativeInteger
n = this.uint16();
a = 0;
while (n--) {
a *= 0x100;
a += this.next();
}
return a;
case 8: // Float
return this.float64();
case 9: // String
case 10: // Symbol
case 14: // UTF8
a = [].slice.call(this.readBytes(n = this.uint32()));
while (n--) {
a[n] = String.fromCharCode(a[n]);
}
return a.join('');
case 11: // ByteArray
return this.readBytes(this.uint32());
case 12: // SoundBuffer
a = [];
n = this.uint32();
while (n--) {
a.push(this.int16());
}
return a;
case 13: // Bitmap
a = [];
a.isBitmap = true;
n = this.uint32();
while (n--) {
a.push(this.uint32());
}
return a;
case 20: // Array
case 21: // OrderedCollection
case 22: // Set
case 23: // IdentitySet
a = [];
n = this.uint32();
while (n--) {
a.push(this.readField());
}
return a;
case 24: // Dictionary
case 25: // IdentityDictionary
a = new sb.Dictionary([], []);
n = this.uint32();
while (n--) {
a.keys.push(this.readField());
a.values.push(this.readField());
}
return a;
case 30: // Color
return new sb.Color(this.uint32(), 255);
case 31: // TranslucentColor
return new sb.Color(this.uint32(), this.uint8());
case 32: // Point
return new sb.Point(this.readField(), this.readField());
case 33: // Rectangle
return new sb.Rectangle(this.readField(), this.readField(), this.readField(), this.readField());
case 34: // Form
return new sb.Form(this.readField(), this.readField(), this.readField(), this.readField(), this.readField());
case 35: // ColorForm
return new sb.ColorForm(this.readField(), this.readField(), this.readField(), this.readField(), this.readField(), this.readField());
}
throw new Error('Invalid fixed-format class ID');
};
p.readHeader = function () {
this.matchBytes([79, 98, 106, 83, 1, 83, 116, 99, 104, 1]);
};
p.readBytes = function (length) {
return this.bytes.subarray(this.position, this.position += length);
};
p.matchBytes = function (bytes) {
var i = bytes.length,
r = this.readBytes(i);
while (i--) {
if (r[i] !== bytes[i]) {
throw new Error('Invalid format');
}
}
};
p.skip = function (length) {
this.position += length;
};
p.next = p.uint8 = function () {
return this.bytes[this.position++];
};
p.hasNext = function () {
return this.position < this.bytes.length;
};
p.uint16 = function () {
return this.next() * 0x100 + this.next();
};
p.uint24 = function () {
return this.next() * 0x10000 + this.next() * 0x100 + this.next();
};
p.uint32 = function () {
return this.next() * 0x1000000 + this.next() * 0x10000 + this.next() * 0x100 + this.next();
};
p.int8 = function () {
var v = this.bytes[++this.position];
return v >= 0x80 ? v - 0x100 : v;
};
p.int16 = function () {
var d = this.next(),
v = d * 0x100 + this.next();
return d >= 0x80 ? v - 0x10000 : v;
};
p.int24 = function () {
var d = this.next(),
v = d * 0x10000 + this.next() * 0x100 + this.next();
return d >= 0x80 ? v - 0x1000000 : v;
};
p.int32 = function () {
var d = this.next(),
v = d * 0x1000000 + this.next() * 0x10000 + this.next() * 0x100 + this.next();
return d >= 0x80 ? v - 0x100000000 : v;
};
p.string = function () {
var length = this.uint16(),
bytes = this.readBytes(length),
i = length;
while (i--) {
bytes[i] = String.fromCharCode(bytes[i]);
}
return bytes.join('');
};
p.float64 = function () {
return this.ieee(8, 11, 52, 1023);
};
p.ieee = function (n, ebits, mbits) {
var bias = (1 << (ebits - 1)) - 1,
string = '',
i = n,
b, sign, exponent, mantissa, result;
while (i--) {
b = this.next().toString(2);
string = string + Array(9 - b.length).join('0') + b;
}
sign = string.charAt(0) === '0' ? 1 : -1;
exponent = parseInt(string.substr(1, ebits), 2);
mantissa = parseInt(string.substr(ebits + 1), 2);
if (exponent === 0) {
return mantissa === 0 ? sign * 0 : sign * Math.pow(2, 1 - bias) * mantissa / Math.pow(2, mbits);
}
if (exponent === (1 << ebits) - 1) {
return mantissa === 0 ? sign / 0 : NaN;
}
return sign * Math.pow(2, exponent - bias) * (1 + mantissa / Math.pow(2, mbits));
};
})(sb.Reader = function () {}, sb.Reader.prototype);
(function (C, p) {
var rotationStyles = {
normal: 1,
leftRight: 2,
none: 0
}, customBlockInputs = {
object: '%obj',
objectList: '%mult%obj',
number: '%n',
numberList: '%mult%n',
text: '%txt',
textList: '%mult%txt',
list: '%l',
listList: '%mult%l',
any: '%s',
anyList: '%mult%s',
'boolean': '%b',
booleanList: '%mult%b',
command: '%cmdRing',
commandList: '%mult%cmdRing',
reporter: '%repRing',
reporterList: '%mult%repRing',
predicate: '%predRing',
predicateList: '%mult%predRing',
loop: '%cs',
loopList: '%mult%cs',
unevaluated: '%anyUE',
unevaluatedList: '%mult%anyUE',
unevaluatedBoolean: '%boolUE',
unevaluatedBooleanList: '%mult%boolUE',
template: '%upvar'
}, blockSelectors = {
// Motion': '',
'forward:': 'forward',
'turnLeft:': 'turnLeft',
'turnRight:': 'turn',
'heading:': 'setHeading',
'pointTowards:': 'doFaceTowards',
'gotoX:y:': 'gotoXY',
'gotoSpriteOrMouse:': 'doGotoObject',
'glideSecs:toX:y:elapsed:from:': 'doGlide',
'changeXposBy:': 'changeXPosition',
'xpos:': 'setXPosition',
'changeYposBy:': 'changeYPosition',
'ypos:': 'setYPosition',
'bounceOffEdge': 'bounceOffEdge',
'xpos': 'xPosition',
'ypos': 'yPosition',
'heading': 'direction',
// Looks
'lookLike:': 'doSwitchToCostume',
'showBackground:': 'doSwitchToCostume',
'nextCostume': 'doWearNextCostume',
'nextBackground': 'doWearNextCostume',
'costumeIndex': 'getCostumeIdx',
'say:duration:elapsed:from:': 'doSayFor',
'say:': 'bubble',
'think:duration:elapsed:from:': 'doThinkFor',
'think:': 'doThink',
'changeGraphicEffect:by:': 'changeEffect',
'setGraphicEffect:to:': 'setEffect',
'filterReset': 'clearEffects',
'setSizeTo:': 'setScale',
'changeSizeBy:': 'changeScale',
'scale': 'getScale',
'show': 'show',
'hide': 'hide',
'comeToFront': 'comeToFront',
'goBackByLayers:': 'goBack',
// Sound
'playSound:': 'playSound',
'doPlaySoundAndWait': 'doPlaySoundUntilDone',
'stopAllSounds': 'doStopAllSounds',
// 'drum:duration:elapsed:from:': '',
'rest:elapsed:from:': 'doRest',
'noteOn:duration:elapsed:from:': 'doPlayNote',
// 'midiInstrument:': '',
// 'changeVolumeBy:': '',
// 'setVolumeTo:': '',
// 'volume': '',
'changeTempoBy:': 'doChangeTempo',
'setTempoTo:': 'doSetTempo',
'tempo': 'getTempo',
// Pen
'clearPenTrails': 'clear',
'putPenDown': 'down',
'putPenUp': 'up',
'penColor:': 'setColor',
'changePenHueBy:': 'changeHue',
'setPenHueTo:': 'setHue',
'_changePenHueBy:': 'changeHue',
'_setPenHueTo:': 'setHue',
'changePenShadeBy:': 'changeBrightness',
'setPenShadeTo:': 'setBrightness',
'changePenSizeBy:': 'changeSize',
'penSize:': 'setSize',
'stampCostume': 'doStamp',
// Control
// 'whenStartClicked': '',
// 'whenKeyPressed:': '',
// 'whenSpriteClicked': '',
'wait:elapsed:from:': 'doWait',
'doForever': 'doForever',
'doRepeat': 'doRepeat',
'broadcast:': 'doBroadcast',
'doBroadcastAndWait': 'doBroadcastAndWait',
// 'whenMessageReceived:': '',
// TODO 'doForeverIf': '',
'doIf': 'doIf',
'doIfElse': 'doIfElse',
'doWaitUntil': 'doWaitUntil',
'doUntil': 'doUntil',
'doReturn': 'doStop',
'stopAll': 'doStopAll',
'doRun': 'doRun',
'doRunBlockWithArgs': 'doRun',
'doRunBlockWithArgList': 'doRun',
'doFork': 'fork',
'doForkBlockWithArgs': 'fork',
'doForkBlockWithArgList': 'fork',
'doReport': 'evaluate',
'doCallBlockWithArgs': 'evaluate',
'doCallBlockWithArgList': 'evaluate',
'doAnswer': 'doReport',
'doStopBlock': 'doStopBlock',
// 'doPauseThread': '',
// 'doPauseThreadReporter': '',
// Sensing
'touching:': 'reportTouchingObject',
'touchingColor:': 'reportTouchingColor',
'color:sees:': 'reportColorIsTouchingColor',
'doAsk': 'doAsk',
'answer': 'reportLastAnswer',
'mouseX': 'reportMouseX',
'mouseY': 'reportMouseY',
'mousePressed': 'reportMouseDown',
'keyPressed:': 'reportKeyPressed',
'distanceTo:': 'reportDistanceTo',
'timerReset': 'doResetTimer',
'timer': 'reportTimer',
'getAttribute:of:': 'reportAttributeOf',
// 'attribute:of:': '',
// 'soundLevel': '',
// 'isLoud': '',
// 'sensor:': '',
// 'sensorPressed:': '',
// 'getObject:': '',
// 'get:': '',
// Operators
'+': 'reportSum',
'-': 'reportDifference',
'*': 'reportProduct',
'/': 'reportQuotient',
'randomFrom:to:': 'reportRandom',
'<': 'reportLessThan',
'=': 'reportEquals',
'>': 'reportGreaterThan',
'&': 'reportAnd',
'|': 'reportOr',
'not': 'reportNot',
'getTrue': 'reportTrue',
'getFalse': 'reportFalse',
'concatenate:with:': 'reportJoinWords',
'letter:of:': 'reportLetter',
'stringLength:': 'reportStringSize',
'asciiCodeOf:': 'reportUnicode',
'asciiLetter:': 'reportUnicodeAsLetter',
'\\\\': 'reportModulus',
'rounded': 'reportRound',
'computeFunction:of:': 'reportMonadic',
'isObject:type:': 'reportIsA',
// 'procedure': 'reifyScript',
// 'procedureWithArgs': 'reifyScript',
// 'function': 'reifyReporter',
// 'functionWithArgs': 'reifyReporter',
// 'spawn': '',
// Variables
'setVar:to:': 'doSetVar',
'changeVar:by:': 'doChangeVar',
// 'deleteObject:': '',
'showVariable:': 'doShowVar',
'hideVariable:': 'doHideVar',
'doDeclareVariables': 'doDeclareVariables',
'newList:': 'reportNewList',
'append:toList:': 'doAddToList',
'deleteLine:ofList:': 'doDeleteFromList',
'insert:at:ofList:': 'doInsertInList',
'setLine:ofList:to:': 'doReplaceInList',
'getLine:ofList:': 'reportListItem',
'lineCountOfList:': 'reportListLength',
'list:contains:': 'reportListContainsItem',
// 'contentsOfList:': '',
// 'copyOfList:': ''
// Kludge
_warp: 'doWarp'
};
function escapeXML(string) {