-
Notifications
You must be signed in to change notification settings - Fork 4
/
nano-ide.js
2384 lines (1959 loc) · 80.8 KB
/
nano-ide.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
/* By Morgan McGuire @CasualEffects http://casual-effects.com GPL 3.0 License*/
// 'IDE', 'Emulator', or 'Minimal'. Emulator will use the minimal style if the page is too
// small for it. See also setUIMode.
var displayMode = 'IDE';
// Must match nano-runtime.js
var SCREEN_WIDTH, SCREEN_HEIGHT, BAR_HEIGHT, BAR_SPACING, FRAMEBUFFER_HEIGHT;
function clamp(x, lo, hi) { return Math.min(Math.max(x, lo), hi); }
function afterImageLoad(url, callback) {
var image = new Image();
image.onload = function () { callback(image); };
image.src = url;
}
var deployed = (location.href.substring(0, 8) !== 'file:///') && (location.href.indexOf('://localhost') === -1);
// The gif recording object, if in a recording
var gifRecording = null;
// Specified as HTML colors for convenience, but converted to ImageData format at the end of
// this script
var screenPalette = new Uint32Array(
// PICO-8 ordering, with some colors replaced
// by Dawnbringer-16 and a more pure white
[0x000000, 0x201590, 0x7E2553, 0x008751, // 00-03
0x8d5432, 0x5E5B69, 0xD8D6D1, 0xFFFDFA, // 04-07
0xFF154A, 0xffaf15, 0xFFEC27, 0x7ce402, // 08-11
0x30AFFF, 0xA99FAD, 0xFF6889, 0xFFCCAC, // 12-15
// Supplemental colors
0xbf0217, 0xd04648, 0xff6600, 0xd27d2c, // 16-19
0xd2aa94, 0xb5b333, 0x6daa2c, 0x346524, // 20-23
0x104510, 0x1becf4, 0x224edc, 0x4a2738, // 24-27
0x6c0daf, 0x9500fd, 0xdf0ac4, 0x303136]);// 28-31
/** The source code for the reset animation. This must compile to something where newlines can
be replaced with semi-colons so that it can become a single JavaScript line after
compilation. So, do not split expressions across newlines in this nano source. */
var resetAnimationNanoSource = `#nanojam Reset,1
// flash at start
if(¬τ)clr=∅;for(i<7)cls(gray(⅗-⅙i));show
// fade
v=(1-|¼²τ-1|)^¼
// rainbow
for(i<2⁷)x=64ξ;pset(x∩62,64ξ∩62,hsv(⅛²x,1,v*i∩1))
// logo
for(j<3)for(i<15)pset(38-i,30+j,gray(v*([8738,21845,21330]ⱼ▻i∩1)))
// hold black and then erase variables and end
if(τ>31)cls(clr=0);i=j=x=v=∅
τ%=40`;
var initialSource =
//tests.forwith;
//tests.customSprite;
//tests.customRotate;
//tests.debug;
//tests.textstyle;
//tests.starattack;
//tests.indent;
//tests.circles;
//tests.nanoBoot;
//tests.nanoReset;
//tests.rgb;
//tests.text;
//tests.triangles;
//tests.spacedash;
//tests.nest;
//tests.scope;
//tests.square;
//tests.WITH;
//tests.triangle;
//tests.textbots;
//tests.stars;
//tests.variables;
//tests.runner;
//tests.hash;
//tests.plasma;
//tests.plasma2;
//tests.manySprites;
//tests.FCN;
//tests.sort;
//tests.ping;
//tests.IF;
//tests.keyrepeat;
//tests.FOR;
tests.input;
//tests.agent;
//tests.rect;
//tests.colorgrid;
if (! deployed) {
document.getElementById('header').innerHTML += '<a style="text-decoration: underline; cursor:pointer" onclick="onRunTests()">Run Tests</a>';
}
/** If null, use HTML Audio tags. Otherwise, use web audio support, which has more features and
lower latency. Implementation from codeheart.js */
var _ch_audioContext;
var _ch_isLocal = (window.location.toString().substr(0, 7) === "file://");
var _ch_isChrome = (navigator.userAgent.toLowerCase().indexOf("chrome") !== -1);
if (! (_ch_isLocal && _ch_isChrome)) {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
if (window.AudioContext) {
try {
_ch_audioContext = new AudioContext();
_ch_audioContext.gainNode = _ch_audioContext.createGain();
_ch_audioContext.gainNode.gain.value = 0.2;
_ch_audioContext.gainNode.connect(_ch_audioContext.destination);
} catch(e) {
console.log(e);
}
}
}
function getQueryString(field) {
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(location.href);
return string ? string[1] : null;
}
function setUIMode(d, noAutoPlay) {
displayMode = d;
let body = document.getElementsByTagName("body")[0];
if (displayMode === 'IDE') {
body.classList.remove('noIDE');
body.classList.remove('minimalUI');
} else {
// Minimal and Emulator
body.classList.add('noIDE');
// Nothing to do except play in this mode, so hit play automatically
if (deployed && ! noAutoPlay) { onPlayButton(); }
}
if ((displayMode !== 'IDE') && deployed) {
// Full-screen the UI
//(body.requestFullscreen || body.webkitRequestFullscreen || body.mozRequestFullScreen || body.msRequestFullscreen || Math.cos)();
if (body.requestFullscreen) {
body.requestFullscreen();
} else if (body.webkitRequestFullscreen) {
body.webkitRequestFullscreen();
} else if (body.mozRequestFullScreen) {
body.mozRequestFullScreen();
} else if (body.msRequestFullscreen) {
body.msRequestFullscreen();
}
}
onResize();
// Reset keyboard focus
emulatorKeyboardInput.focus();
}
function onResize() {
let body = document.getElementsByTagName('body')[0];
let emulator = document.getElementById('emulator');
switch (displayMode) {
case 'IDE':
// Remove explicit styles set by Javascript
// for the minimal UI.
emulator.removeAttribute('style');
break;
case 'Emulator':
// If not too small, remove minimalUI from body
// TODO
body.classList.remove('minimalUI');
// Remove explicit styles set by Javascript
// for the minimal UI.
emulator.removeAttribute('style');
// If too small, fall through to minimal
// TODO
break;
case 'Minimal':
// What is the largest multiple FRAMEBUFFER_HEIGHT that is less than windowHeightDevicePixels?
let scale = Math.max(0, Math.min((window.innerHeight - 40) / 300, (window.innerWidth - 270) / 280));
if (scale * window.devicePixelRatio <= 2.5) {
// Round to nearest even multiple of the actual pixel size for small screens to
// keep per-pixel accuracy
scale = Math.floor(scale * window.devicePixelRatio) / window.devicePixelRatio;
}
// Setting the scale transform triggers really slow rendering on Raspberry Pi unless we
// add the "translate3d" hack to trigger hardware acceleration.
emulator.style.transform = 'scale(' + scale + ') translate3d(0,0,0)';
emulator.style.left = Math.round((window.innerWidth - emulator.offsetWidth) / 2) + 'px';
emulator.style.top = '8px';
// Hide emulator elements
body.classList.add('minimalUI');
break;
}
}
window.addEventListener("resize", onResize, false);
function onUIModeMenuButton(event) {
let menu = document.getElementById('uiModeMenu');
if (menu.style.visibility === 'visible') {
menu.style.visibility = 'hidden';
} else {
menu.style.visibility = 'visible';
}
event.stopPropagation();
}
function getImageData(image) {
var tempCanvas = document.createElement('canvas');
tempCanvas.width = image.width;
tempCanvas.height = image.height;
var tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(image, 0, 0, image.width, image.height);
return tempCtx.getImageData(0, 0, image.width, image.height);
}
/** Returns a 5-level grayscale Uint8Array of this data */
function getPixelData5(image) {
var imageData = getImageData(image);
// Extract and copy
var N = imageData.data.length / 4;
var pixelData = new Uint8Array(N);
pixelData.width = image.width;
pixelData.height = image.height;
for (var i = 0; i < N; ++i) {
var r = imageData.data[i * 4];
// Convert red value to 0,1,2,3,4.
var c = Math.round(0.12 + r / 64);
pixelData[i] = c;
}
// Throw away the data used for conversion to an array
imageData = null;
return pixelData;
}
var fontPixelData = null;
(function() {
var fontSheetImage = new Image();
fontSheetImage.onload = function () {
fontPixelData = getPixelData5(fontSheetImage);
};
fontSheetImage.src = 'font.png';
})();
/** The sprite sheet. Always 128px wide. Currently 64px high. Shared with Runtime */
var spritePixelData = null;
afterImageLoad('sprites.png', function (spriteSheetImage) {
// 8x8 sprites scaled up by 3x
spritePixelData = getPixelData5(spriteSheetImage);
// Draw on the display canvas
var spritesDisplay = document.getElementById('spritesDisplay');
spritesDisplay.width = spriteSheetImage.width * 3;
spritesDisplay.height = spriteSheetImage.height * 3;
spritesDisplay.style.width = spritesDisplay.width + 'px';
spritesDisplay.style.height = spritesDisplay.height + 'px';
spritesDisplay.onclick = onSpriteSelect;
var sctx = spritesDisplay.getContext("2d");
sctx.imageSmoothingEnabled = false;
sctx.webkitImageSmoothingEnabled = false;
sctx.drawImage(spriteSheetImage, 0, 0, spritesDisplay.width, spritesDisplay.height);
sctx.strokeStyle = "#050";
for (var x = 1; x < 16; ++x) {
sctx.moveTo(x * 3 * 8, 0);
sctx.lineTo(x * 3 * 8, spritesDisplay.height);
sctx.stroke();
}
for (var y = 1; y < 8; ++y) {
sctx.moveTo(0, y * 3 * 8);
sctx.lineTo(spritesDisplay.width, y * 3 * 8);
sctx.stroke();
}
setTimeout(redrawSelectedSprite, 500);
});
// For the sprite window
var selectedSpriteIndex = 0;
function onSpriteSelect(event) {
// 8x8 sprites scaled up by 3x
var x = clamp(Math.floor(event.offsetX / (3 * 8)), 0, 15);
var y = clamp(Math.floor(event.offsetY / (3 * 8)), 0, 7);
selectedSpriteIndex = x + y * 16;
redrawSelectedSprite();
}
function rgb(r,g,b,x,y) {
var dither = (y !== undefined);
x |= 0; y |= 0;
// Convert to 8-bit
r = clamp((r * 256) | 0, 0, 255) | 0; g = clamp((g * 256) | 0, 0, 255) | 0; b = clamp((b * 256) | 0, 0, 255) | 0;
var closestIndex = -1, secondClosestIndex = -1, colorDistance = 1000000, secondDistance = 100000;
for (var i = screenPalette.length - 1; i >= 0; --i) {
var c = screenPalette[i] | 0;
var dist = squaredColorDistance(c & 0xff, (c >> 8) & 0xff, (c >> 16) & 0xff, r, g, b) | 0;
if (dist < colorDistance) {
secondDistance = colorDistance; secondClosestIndex = closestIndex;
colorDistance = dist; closestIndex = i;
} else if (dist < secondDistance) {
secondDistance = dist; secondClosestIndex = i;
}
}
// Dither closest and second closest when close. Multiply by 3 and 2 to avoid
// multiplying by 1.5 and becoming doubles. Use the closestIndex as a hash
// for the dithering pattern to reduce the number of cases where two patterns
// that have the same color in them misalign and end up with doubled pixels.
if (dither && ((x ^ y ^ closestIndex) & 1) &&
(((colorDistance * 3) | 0) > (secondDistance << 1))) {
closestIndex = secondClosestIndex;
}
return closestIndex;
}
function redrawSelectedSprite() {
var localPalette = [Runtime.TRANSPARENT, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var swizzle = document.getElementById('spriteColormap').value;
// Remove leading 0s so it doesn't parse as octal, and
// convert NaNs back to zero
colormap = parseInt(swizzle.replace(/^0+/, '')) || 0;
for (var slot = 0; slot < 4; ++slot) {
var c = paletteToolCurrentPalette[0] = paletteToolCurrentPalette[colormap % 10];
localPalette[4 - slot] = c;
colormap = (colormap / 10) | 0;
}
// Choose a background color that isn't in the current palette so that
// all colors will be mostly visible.
var fill = 0;
for (var i = 0; i < 6; ++i) {
var ok = true;
for (var j = 0; j < 7; ++j) {
ok = ok && (paletteToolCurrentPalette[j] !== i);
}
if (ok) { fill = i; break; }
}
var pi = Math.PI;
var special = [0, '0',
pi/2, '½π',
pi/3, '⅓π',
2*pi/3, '⅔π',
pi/4, '¼π',
3*pi/4, '¾π',
pi/5,'⅕π',
2*pi/5,'⅖π',
3*pi/5,'⅗π',
4*pi/5, '⅘π',
pi/6, '⅙π',
pi/7, '⅐π',
pi/8, '⅛π',
pi/9, '⅑π',
pi/10, '⅒π',
pi, 'π'];
var xform = (document.getElementById('selectedSpriteDiagonalButton').checked ? 1 : 0) |
(document.getElementById('selectedSpriteHorizontalButton').checked ? 2 : 0) |
(document.getElementById('selectedSpriteVerticalButton').checked ? 4 : 0);
var rot = document.getElementById('selectedSpriteAngle').value * pi / 180;
// Snap to any nearby representable values for printing purposes,
// and also snap the slider (only needed on Firefox)
// Reduce the precision of rot to three decimal places for printing
var rotStr = '' + (Math.round(rot * 1000) / 1000);
// Remove optional leading zero
if (rotStr.substring(0,2) === '0.') { rotStr = rotStr.substring(1); }
for (var i = 0; i < special.length; i += 2) {
if (Math.abs(special[i] - Math.abs(rot)) < 0.15) {
rot = Math.sign(rot) * special[i];
document.getElementById('selectedSpriteAngle').value = rot * 180 / pi;
rotStr = ((rot < 0) ? '-' : '') + special[i + 1];
break;
}
}
if (Runtime && Runtime._draw && Runtime._spriteSheet) {
let N = SCREEN_WIDTH * FRAMEBUFFER_HEIGHT;
let screenData = new Uint8Array(N);
screenData.fill(fill);
Runtime._draw(selectedSpriteIndex, 6, 6, localPalette, xform, rot, screenData, 0, 0, 63, 63);
// Expand the paletted image to RGB values
// Overwrite the entire image for simplicity, even though we only need the upper 12x12
let data = Runtime._updateImageDataUint32;
for (var i = 0; i < N; ++i) {
data[i] = screenPalette[screenData[i]];
}
// Copy screen to context (reusing the updateImage context from the main engine)
updateImage.getContext('2d').putImageData(updateImageData, 0, 0);
// Blit to the selectedSprite canvas, enlarging it as we go
var selectedSprite = document.getElementById('selectedSprite');
var sctx = selectedSprite.getContext('2d');
sctx.imageSmoothingEnabled = false;
sctx.webkitImageSmoothingEnabled = false;
sctx.drawImage(updateImage, 0, 0, 14, 14, 4, 4, 14*4, 14*4);
}
let cmd = 'draw(' + selectedSpriteIndex + ',32,32';
cmd += ',' + swizzle.replace(/^0+([^0])/, '$1');
if (rotStr !== '0' || xform !== 0) {
cmd += ',' + xform;
}
if (rotStr !== '0') {
cmd += ',' + rotStr;
}
cmd += ')';
document.getElementById('spriteCmd').value = cmd;
}
document.getElementById('selectedSpriteDiagonalButton').onclick = document.getElementById('selectedSpriteHorizontalButton').onclick = document.getElementById('selectedSpriteVerticalButton').onclick = redrawSelectedSprite;
function makeSymbolsWindow() {
var chars =
`½⅓⅔¼¾⅕⅖⅗⅘⅙⅐⅛⅑⅒ %^*/-+ {};
επτ∞∅ξΔαβγδζηθλιμρσϕχψωΩ
∩∪⊕~◅▻¬ &X ≟≠≤≥<> =∊ ⌊⌋|⌈⌉
⁰¹²³⁴⁵⁶⁷⁸⁹ ⁽⁾⁻⁺ ᵃᵝⁱʲˣᵏᵘⁿ
₀₁₂₃₄₅₆₇₈₉ ₍₎₋₊ ₐᵦᵢⱼₓₖᵤₙ`;
var tooltipTable = {
'%': 'modulo',
'^': 'exponent',
'*': 'multiplication',
'/': 'division',
'-': 'subtraction',
'+': 'addition/string concatenation',
';': 'statement separator',
'ε': 'small value (\\epsilon)',
'π': 'constant 3.14... (\\pi)',
'τ': 'integer time in frames (\\tau)',
'∞': 'infinity (\\infty)',
'∅': 'nil (\\nil)',
'ξ': 'random (\\xi)',
'Δ': 'variable prefix (\\Delta)',
'α': 'variable (\\alpha)',
'β': 'variable (\\beta)',
'γ': 'variable (\\gamma)',
'δ': 'variable (\\delta)',
'ζ': 'variable (\\zeta)',
'η': 'variable (\\eta)',
'ι': 'variable (\\iota)',
'λ': 'variable (\\lambda)',
'μ': 'variable (\\mu)',
'ρ': 'variable (\\rho)',
'σ': 'variable (\\sigma)',
'ϕ': 'variable (\\phi)',
'χ': 'variable (\\chi)',
'ψ': 'variable (\\psi)',
'ω': 'variable (\\omega)',
'Ω': 'variable (\\Omega)',
'{': 'begin table',
'}': 'end table',
'∩': 'bitwise and',
'∪': 'bitwise or',
'⊕': 'bitwise xor',
'~': 'bitwise not',
'◅': 'bit shift left (<<)',
'▻': 'bit shift right (>>)',
'¬': 'logical not (\\not)',
'&': 'logical and',
'X': 'logical or',
'⌊': 'floor (\\lfloor)',
'⌋': 'floor (\\rfloor)',
'|': 'absolute value',
'⌈': 'ceiling (\\lceil)',
'⌉': 'ceiling (\\rceil)',
'≟': 'equals (?=)',
'≠': 'not equal/logical xor (!=)',
'∊': 'FOR-loop in (\\in)',
'=': 'assignment',
'≤': 'compare (\\leq)',
'≥': 'compare (\\geq)',
'⁰': 'exponent',
'₀': 'array index'
};
var tooltip = 'fraction'
var s = '';
var line = 0;
for (var i = 0; i < chars.length; ++i) {
var c = chars[i];
tooltip = tooltipTable[c] || tooltip;
switch (c) {
case '\n': s += '<br>'; ++line; break;
case ' ': s += '<span style="display:inline-block;width:' + (12) + 'px"> </span>'; break;
default:
if (c === 'X') c = 'or';
s += '<div onmousedown="event.stopPropagation()" class="button" title="' + tooltip + '" onclick="insertSymbol(\'' + c + '\')"><label><span class="label"><span>' + c + '</span></span></label></div>';
}
}
document.getElementById('keys').innerHTML = s;
}
/** Filled out by makeSoundsWindow */
var soundArray = [];
function makeSoundsWindow() {
var s = '';
var type = ['Coin', 'Shoot', 'Explode', 'Powerup', 'Hit', 'Jump', 'Blip', 'Wild'];
for (let i = 0; i < type.length; ++i) {
s += '<div style="margin-bottom:5px; width:60px; text-align:left; display: inline-block; position: relative; top: -7px">' + type[i] + '</div>';
for (let j = 0; j < 10; ++j) {
let num = i * 10 + j;
let numStr = (i == 0 ? '0' : '') + num;
soundArray.push(loadSound('sounds/' + numStr + '-' + type[i] + '.mp3'));
s += '<div onmousedown="event.stopPropagation()" class="button" onclick="playSoundNum(\'' + num + '\')"><label><span class="label"><span>' + numStr + '</span></span></label></div>';
} // j
s += '<br>';
} // i
document.getElementById('sounds').innerHTML = s;
}
// Allow the rest of the loading to complete before trying to load all of the sounds
setTimeout(makeSoundsWindow, 0);
makeSymbolsWindow();
/** SymbolsWindow callback */
function insertSymbol(s) {
editor.session.replace(editor.selection.getRange(), s);
// Restore focus to the editor
editor.focus();
}
// Use only MP3s
function loadSound(url) {
if (_ch_audioContext) {
// Use asynchronous loading
let sound = Object.seal({ src: url,
loaded: false,
source: null,
buffer: null,
playing: false });
let request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
_ch_audioContext.decodeAudioData(
request.response,
function onSuccess(buffer) {
sound.buffer = buffer;
sound.loaded = true;
// Create a buffer, which primes this sound for playing
// without delay later.
sound.source = _ch_audioContext.createBufferSource();
sound.source.buffer = sound.buffer;
sound.source.connect(_ch_audioContext.gainNode);
},
function onFailure() {
console.warn("Could not load sound " + url);
});
};
sound.playing = false;
request.send();
return sound;
} else {
// Legacy and local Chrome path
let s = new Audio();
s.src = url;
s.volume = 0.2;
s.preload = "auto";
s.playing = false;
s.onended = function() { s.playing = false; };
s.onpause = s.onended;
s.load();
return s;
}
}
function playSoundNum(n) {
if (soundArray.length > 0) {
playSound(soundArray[Math.max(0, Math.min(n | 0, soundArray.length - 1))], false);
}
}
function playSound(sound, loop) {
// Ensure that the value is a boolean
loop = loop ? true : false;
if (_ch_audioContext) {
// Chrome creates the audio context paused if it was
// originally made on page load--resume it.
_ch_audioContext.resume();
if (sound.loaded) {
// A new source must be created every time that the sound is played
sound.source = _ch_audioContext.createBufferSource();
sound.source.buffer = sound.buffer;
sound.source.connect(_ch_audioContext.gainNode);
sound.source.loop = loop;
sound.source.onended = function () {
sound.source = null;
sound.playing = false;
};
if (! sound.source.start) {
// Backwards compatibility
sound.source.start = sound.source.noteOn;
sound.source.stop = sound.source.noteOff;
}
sound.playing = true;
sound.source.start(0);
}
} else {
// Legacy support
try {
// Reset the sound
if (! loop) {
sound.currentTime = 0;
}
// Avoid changing properties unless required because the
// browser's implementation may be inefficient.
if (sound.loop != loop) {
sound.loop = loop;
}
// Only play if needed
if (! loop || sound.paused || sound.ended) {
sound.play();
sound.playing = true;
}
} catch (e) {
// Ignore invalid state error if loading has not succeeded yet
}
} // web audio
}
var paletteToolCurrentPalette = [7, 7, 13, 0, 8, 10, 12, 11, 29, 32];
afterImageLoad('rainbow-selector.png', function (rainbowImage) {
var rainbowImageData = getImageData(rainbowImage);
// VERY approximate brightness on [0, 255]. c is in imageData format.
function brightness(c) {
return 0.3 * (c & 0xff) + 0.6 * ((c >> 8) & 0xff) + 0.1 * ((c >> 16) & 0xff);
}
var s = '';
for (var i = 0; i < 32; ++i) {
var c = imageDataToHTMLColorString(screenPalette[i]);
s += '<div class="colorswatch draggable" draggable="true" onmousedown="event.stopPropagation()" ' +
' ondragstart="colorDragStart(event)" style="' +
(i === 0 ? 'border-radius: 6px 0 0 0;' : '') +
(i === 15 ? 'border-radius: 0 6px 0 0;' : '') +
(brightness(screenPalette[i]) < 128 ? 'color:#fff;' : '') +
'background:' + c + '">' + i + '</div>';
if (i === 15) { s += '<br>'; }
}
s += '<div style="line-height:5px; margin-top:8px; overflow:hidden; height:90px">';
for (var y = 0; y < rainbowImageData.height; ++y) {
for (var x = 0; x < rainbowImageData.width; ++x) {
var idx = (x + y * rainbowImageData.width) * 4;
var r = rainbowImageData.data[idx], g = rainbowImageData.data[idx + 1], b = rainbowImageData.data[idx + 2];
// Snap to nano colors
var colorIndex = rgb(r / 255, g / 255, b / 255);
var htmlColor = imageDataToHTMLColorString(screenPalette[colorIndex]);
s += '<div class="tinycolorswatch draggable" draggable="true" onmousedown="event.stopPropagation()" ' +
' ondragstart="colorDragStart(event)" style="background:' + htmlColor + '"></div>';
}
if (y < rainbowImageData.height - 1) { s += '<br>'; }
}
s+= '</div>';
s += '<div style="position: absolute; top: 166px; left: 40px"><span style="position:relative; top:4px">Palette</span> ';
for (var i = 9; i >= 0; --i) {
var style = '';
if ((i >= 1) && (i < 9)) {
var c = imageDataToHTMLColorString(screenPalette[paletteToolCurrentPalette[i]]);
style = ' style="background:' + c + '" ';
} else if (i === 9) {
style = ' title="Transparent" ';
} else if (i === 0) {
style = ' title="Previous" ';
}
s += '<div class="paletteSlot" ondragover="event.preventDefault()" ' + ((i > 0 && i < 9) ? 'ondrop="colorDragDrop(event)"' : '') + ' id="paletteSlot' + i + '"' + style + '>' + i + '</div>';
}
s += '</div>';
s += '<input type="text" class="cmd" id="palCmd" onmousedown="event.stopPropagation()" onchange="onPalCmdChange(event)">';
document.getElementById('paletteTray').innerHTML = s;
updatePaletteToolCmd();
});
function onPalCmdChange(event) {
var m = event.target.value.trim().match(/(?:pal\()?(\d+)\)?/);
if (m) {
c = parseInt(m[1]);
if (! isNaN(c)) {
for (var i = 1; i < 7; ++i) {
paletteToolCurrentPalette[i] = c % 100;
c = Math.floor(c / 100);
document.getElementById('paletteSlot' + i).style.background = imageDataToHTMLColorString(screenPalette[paletteToolCurrentPalette[i]]);
}
}
}
updatePaletteToolCmd();
redrawSelectedSprite();
}
function colorDragStart(event) {
var swatch = event.target;
// Pull the color off the RGB of the background.
var color = parseColor(window.getComputedStyle(swatch, null).getPropertyValue("background-color"));
// Needed for Firefox to render the component
event.dataTransfer.setData('color', JSON.stringify(color));
}
function colorDragDrop(event) {
var color = event.dataTransfer.getData('color');
if (! color) { return; }
color = JSON.parse(color);
// Find closest nano color
var colorIndex = rgb(color.r, color.g, color.b);
event.target.style.background = 'rgb(' + (color.r * 255) + ', ' + (color.g * 255) + ', ' + (color.b * 255) + ')';
var paletteSlotIndex = parseInt(event.target.innerText);
paletteToolCurrentPalette[paletteSlotIndex] = colorIndex;
updatePaletteToolCmd();
redrawSelectedSprite();
}
function updatePaletteToolCmd() {
var s = ')';
for (var i = 1; i < 9; ++i) {
var c = paletteToolCurrentPalette[i];
s = c + s;
if (c < 10) {
s = '0' + s;
}
}
s = s.replace(/^0+([^0])/, '$1');
s = 'pal(' + s;
document.getElementById('palCmd').value = s;
}
(function() {
// Switch base palette HTML RGB format to ImageData little-endian ABGR format after the
// palette GUI is constructed.
for (var i = 0; i < screenPalette.length; ++i) {
screenPalette[i] = htmlColorIntegerToImageData(screenPalette[i]);
}
})();
//////////////////////////////////////////////////////////////////////////////////
function cartridgeDragStart(event) {
// Needed for Firefox to render the component
event.dataTransfer.setData('text/plain', null);
}
function cartridgeDragEnd(event) {
}
//////////////////////////////////////////////////////////////////////////////////
var DragLib = function() {
return {
move : function(element, xpos, ypos){
element.style.left = xpos + 'px';
element.style.top = ypos + 'px';
},
startMoving : function(element, evt) {
evt = evt || window.event;
var container = element.parentNode;
var x0 = element.offsetLeft,
y0 = element.offsetTop,
maxX = container.getBoundingClientRect().width - element.getBoundingClientRect().width,
maxY = container.getBoundingClientRect().height - element.getBoundingClientRect().height;
// Workaround for the container height returning low numbers for the body
maxY = 1080;
container.style.cursor = 'move';
// Initial click offset
var diffX = evt.clientX - x0, diffY = evt.clientY - y0;
document.onmousemove = function(evt) {
evt = evt || window.event;
DragLib.move(element,
Math.min(Math.max(evt.clientX - diffX, 0), maxX),
Math.min(Math.max(evt.clientY - diffY, 0), maxY));
}
},
stopMoving : function(element) {
element.parentNode.style.cursor = 'default';
document.onmousemove = null;
},
}
}();
var nanoScreen = document.getElementById("screen");
var ctx = nanoScreen.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
var bar = document.getElementById("bar");
var barCtx = bar.getContext("2d");
barCtx.imageSmoothingEnabled = false;
barCtx.webkitImageSmoothingEnabled = false;
function onHelp(event) { window.open('doc/specification.md.html', '_blank'); }
function download(url, name) {
var a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
setTimeout(function() {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0);
}
function getTitle(src) {
var match = src.match(/^#nanojam[ \t]+(..+?)((?:,)([ \t]*\d+[ \t]*))?\n/);
if (match) {
return match[1].trim();
} else {
return 'Untitled';
}
}
function getFlags(src) {
var match = src.match(/^#nanojam[ \t]+(..+?)((?:,)([ \t]*\d+[ \t]*))?\n/);
if (match && (match[3] !== undefined)) {
return parseInt(match[3].trim()) || 0;
} else {
return 0;
}
}
function replaceTitle(code, newTitle) {
var match = code.match(/^#nanojam[ \t]+(..+?)(,([ \t]*\d+[ \t]*))?/);
if (match) {
return '#nanojam ' + newTitle + (match[2] || '').trim() + '\n' + code.replace(/^.*\n/, '');
} else {
return code;
}
}
function getFilename(title) {
title = title || '';
return title.trim().replace(/ /g, '_').replace(/[:?"'&<>*|]/g, '') + '.nano';
}
function cartridgeArrayContainsFilename(filename) {
for (var i = 0; i < cartridgeArray.length; ++i) {
if (cartridgeArray[i].filename === filename) {
return true;
}
}
return false;
}
/** Generate a new title that is like oldTitle but does not collide with any filename
already in the Google Drive. */
function generateNewTitle(oldTitle) {
if ((oldTitle === '(NEW CART)') || ! oldTitle) {
if (! cartridgeArrayContainsFilename(getFilename('Untitled'))) {
return 'Untitled';
}
oldTitle = 'Untitled';
}
var i = 2;
var newTitle;
do {
newTitle = oldTitle + ' ' + i;
++i;
} while (cartridgeArrayContainsFilename(getFilename(newTitle)));
return newTitle;
}
function onExportFile(event) {
var src = editor.getValue();
var filename = getFilename(getTitle(src));
if (filename) {
// Convert unicode to a downloadable binary data URL
download(window.URL.createObjectURL(new Blob(['\ufeff', src])), filename);
} else {
alert('The program must begin with #nanojam and a title before it can be exported');
}
}
/** Callback for loading from local disk */
function onImportFile(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function () {
editor.setValue(reader.result);
activeCartridge.title = getTitle(reader.result);
activeCartridge.filename = getFilename();
activeCartridge.flags = getFlags(reader.result);
activeCartridge.readOnly = true;
activeCartridge.googleDriveFileID = undefined;
setChanged(true);
editor.gotoLine(1);
};
reader.readAsText(file);
}
function onRestartButton() {