This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathled.js
1139 lines (1071 loc) · 38.9 KB
/
led.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
/**
* @fileoverview Simulates LEDs
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2020 Jeff Parsons
* @license MIT
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*/
"use strict";
/**
* @typedef {Config} LEDConfig
* @property {string} class
* @property {Object} [bindings]
* @property {number} [version]
* @property {Array.<string>} [overrides]
* @property {number} type (one of the LED.TYPE values)
* @property {number} [width] (the view width of a cell)
* @property {number} [height] (the view height of a cell)
* @property {number} [cols]
* @property {number} [colsExtra] (number of hidden columns, if any, on the right)
* @property {number} [rows]
* @property {number} [rowsExtra] (number of hidden rows, if any, on the bottom; TBD)
* @property {string} [color]
* @property {string} [backgroundColor]
* @property {boolean} [fixed]
* @property {boolean} [hexagonal]
* @property {boolean} [highlight]
* @property {boolean} [persistent]
*/
/**
* The ultimate goal is to provide support for a variety of LED types, such as:
*
* 1) LED Light (single light)
* 2) LED Digit (7-segment digit)
*
* The initial goal is to manage a 12-element array of 7-segment LED digits for the TI-57.
*
* We create a "view" canvas element inside the specified "container" element, along with a "grid" canvas
* where all the real drawing occurs; drawView() then renders the "grid" canvas onto the "view" canvas.
*
* Internally, our LED digits have a width and height of 96 and 128. Those are "grid" dimensions which
* cannot be changed, because our table of drawing coordinates in LED.SEGMENTS are hard-coded for those
* dimensions. The cell width and height that are specified as part of the LEDConfig are "view" dimensions,
* which usually match the grid dimensions, but you're welcome to scale them up or down; the browser's
* drawImage() function takes care of that.
*
* There is a low-level function, drawGridSegment(), for drawing specific LED segments of specific digits;
* generally, you start with clearGrid(), draw all the segments for a given update, and then call drawView()
* to make them visible.
*
* However, our devices operate at a higher level. They use setLEDState() to modify the state,
* character, etc, that each of the LED cells should display, which updates our internal LED buffer. Then
* at whatever display refresh rate is set (typically 60Hz), drawBuffer() is called to see if the buffer
* contents have been modified since the last refresh, and if so, it converts the contents of the buffer to
* a string and calls drawString().
*
* This buffering strategy, combined with the buffer "tickled" flag (see below), not only makes life
* simple for this device, but also simulates how the display goes blank for short periods of time while
* the CPU is busy performing calculations.
*
* @class {LED}
* @unrestricted
* @property {LEDConfig} config
* @property {number} type (one of the LED.TYPE values)
* @property {number} width (default is 96 for LED.TYPE.DIGIT, 32 otherwise; see LED.SIZES)
* @property {number} height (default is 128 for LED.TYPE.DIGIT, 32 otherwise; see LED.SIZES)
* @property {number} cols (default is 1)
* @property {number} rows (default is 1)
* @property {number} colsView (default is cols)
* @property {number} rowsView (default is rows)
* @property {string} color (default is none; ie, transparent foreground)
* @property {string} colorBackground (default is none; ie, transparent background)
* @property {boolean} fFixed (default is false, meaning the view may fill the container to its maximum size)
* @property {boolean} fHexagonal (default is false)
* @property {boolean} fHighlight (default is true)
* @property {boolean} fPersistent (default is false for LED.TYPE.DIGIT, meaning the view will be blanked if not refreshed)
* @property {number} widthView (computed)
* @property {number} heightView (computed)
* @property {number} widthGrid (computed)
* @property {number} heightGrid (computed)
* @property {HTMLCanvasElement} canvasView
* @property {CanvasRenderingContext2D} contextView
* @property {HTMLCanvasElement} canvasGrid
* @property {CanvasRenderingContext2D} contextGrid
* @property {{ container: Element|undefined }} bindings
* @property {Array.<string|number|null>} buffer
* @property {Array.<string|number>|null} bufferClone
* @property {boolean} fBufferModified
* @property {boolean} fBufferTickled
*/
class LED extends Device {
/**
* LED(idMachine, idDevice, config)
*
* Sample config:
*
* "display": {
* "class": "LED",
* "type": 3,
* "cols": 12,
* "rows": 1,
* "color": "red",
* "bindings": {
* "container": "displayTI57"
* }
* }
*
* @this {LED}
* @param {string} idMachine
* @param {string} idDevice
* @param {LEDConfig} [config]
*/
constructor(idMachine, idDevice, config)
{
super(idMachine, idDevice, config, ["color", "backgroundColor"]);
let container = this.bindings[LED.BINDING.CONTAINER];
if (!container) {
let sError = "LED " + this.config.bindings[LED.BINDING.CONTAINER] + " binding for '" + LED.BINDING.CONTAINER + "' missing";
throw new Error(sError);
}
let canvasView = /** @type {HTMLCanvasElement} */ (document.createElement("canvas"));
if (!canvasView || !canvasView.getContext) {
let sError = "LED device requires HTML5 canvas support";
container.innerHTML = sError;
throw new Error(sError);
}
this.container = container;
this.canvasView = canvasView;
this.type = this.getBounded(this.getDefaultNumber('type', LED.TYPE.ROUND, LED.TYPES), LED.TYPE.SMALL, LED.TYPE.DIGIT);
this.widthCell = LED.SIZES[this.type][0];
this.heightCell = LED.SIZES[this.type][1];
this.width = this.getDefaultNumber('width', this.widthCell);
this.height = this.getDefaultNumber('height', this.heightCell);
this.colsView = this.getDefaultNumber('cols', 1);
this.cols = this.colsView + this.getDefaultNumber('colsExtra', 0);
this.rowsView = this.getDefaultNumber('rows', 1);
this.rows = this.rowsView + this.getDefaultNumber('rowsExtra', 0);
this.widthView = this.width * this.colsView;
this.heightView = this.height * this.rowsView;
this.colorTransparent = this.getRGBAColor("black", 0);
this.colorOn = this.getRGBColor(this.config['color']) || this.colorTransparent;
this.colorOff = this.getRGBAColor(this.colorOn, 1.0, 0.25);
this.colorHighlight = this.getRGBAColor(this.colorOn, 1.0, 2.0);
this.colorBackground = this.getRGBColor(this.config['backgroundColor']);
/*
* We generally want our view canvas to be "responsive", not "fixed" (ie, to automatically resize
* with changes to the overall window size), so we apply the following style attributes:
*
* width: 100%;
* height: auto;
*
* But, if you really don't want that feature, then set the LED config's "fixed" property to true.
*/
this.fFixed = this.getDefaultBoolean('fixed', false);
if (!this.fFixed) {
canvasView.style.width = "100%";
canvasView.style.height = "auto";
}
/*
* Hexagonal (aka "Lite-Brite" mode) and highlighting options
*/
this.fHexagonal = this.getDefaultBoolean('hexagonal', false);
this.fHighlight = this.getDefaultBoolean('highlight', true);
/*
* Persistent LEDS are the default, except for LED.TYPE.DIGIT, which is used with calculator displays
* whose underlying hardware must constantly "refresh" the LEDs to prevent them from going dark.
*/
this.fPersistent = this.getDefaultBoolean('persistent', (this.type < LED.TYPE.DIGIT));
canvasView.setAttribute("width", this.widthView.toString());
canvasView.setAttribute("height", this.heightView.toString());
canvasView.style.backgroundColor = this.colorTransparent;
container.appendChild(canvasView);
this.contextView = /** @type {CanvasRenderingContext2D} */ (canvasView.getContext("2d"));
/*
* canvasGrid is where all LED segments are composited; then they're drawn onto canvasView.
*/
this.canvasGrid = /** @type {HTMLCanvasElement} */ (document.createElement("canvas"));
if (this.canvasGrid) {
this.canvasGrid.width = this.widthGrid = this.widthCell * this.colsView;
this.canvasGrid.height = this.heightGrid = this.heightCell * this.rowsView;
this.contextGrid = this.canvasGrid.getContext("2d");
}
/*
* Time to allocate our internal LED buffer. Other devices access the buffer through interfaces
* like setLEDState() and getLEDState(). The LED buffer contains four per elements per LED cell:
*
* [0]: state (eg, ON or OFF or a digit)
* [1]: color
* [2]: count(s) (eg, 0 to 8 4-bit counts)
* [3]: flags (eg, PERIOD, MODIFIED, etc)
*
* The LED buffer also contains an extra (scratch) row at the end. This extra row, along with the
* dynamically allocated "clone" buffer, is used by the LED Controller for direct buffer manipulation;
* see the low-level getBuffer(), getBufferClone(), and swapBuffers() interfaces.
*/
this.nBufferInc = 4;
this.nBufferCells = ((this.rows + 1) * this.cols) * this.nBufferInc;
this.buffer = new Array(this.nBufferCells);
this.bufferClone = null;
this.nBufferIncExtra = (this.colsView < this.cols? (this.cols - this.colsView) * 4 : 0);
/*
* fBufferModified is straightforward: set to true by any setLEDState() call that actually
* changed something in the LED buffer, set to false after every drawBuffer() call, periodic
* or otherwise.
*
* fBufferTickled is a flag which, under normal (idle) circumstances, will constantly be set
* to true by periodic display operations that call setLEDState(); we clear it after every
* periodic drawBuffer(), so if the machine fails to execute a setBuffer() in a timely manner,
* we will see that fBufferTickled hasn't been "tickled", and automatically blank the display.
*
* fDisplayOn is a global "on/off" switch for the entire display.
*/
this.fBufferModified = this.fBufferTickled = false;
this.msLastDraw = 0;
this.fDisplayOn = true;
/*
* nShiftedLeft is an optimization that tells drawGrid() when it can minimize the number of
* individual cells to redraw, by shifting the entire grid image leftward and redrawing only
* the rightmost cells.
*/
this.nShiftedLeft = 0;
/*
* This records the location of the most recent LED buffer location updated via setLEDState(),
* in case we want to highlight it.
*/
this.iBufferRecent = -1;
let led = this;
this.time = /** @type {Time} */ (this.findDeviceByClass("Time"));
this.time.addAnimation(function ledAnimate(t) {
led.drawBuffer(false, t);
});
led.clearBuffer(true);
}
/**
* clearBuffer(fDraw)
*
* @this {LED}
* @param {boolean} [fDraw]
*/
clearBuffer(fDraw)
{
this.initBuffer(this.buffer);
this.fBufferModified = this.fBufferTickled = true;
if (fDraw) this.drawBuffer(true);
}
/**
* clearGrid()
*
* @this {LED}
*/
clearGrid()
{
if (this.colorBackground) {
this.contextGrid.fillStyle = this.colorBackground;
this.contextGrid.fillRect(0, 0, this.widthGrid, this.heightGrid);
} else {
this.contextGrid.clearRect(0, 0, this.widthGrid, this.heightGrid);
}
}
/**
* clearGridCell(col, row, xOffset)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @param {number} xOffset
*/
clearGridCell(col, row, xOffset)
{
let xDst = col * this.widthCell + xOffset;
let yDst = row * this.heightCell;
if (this.colorBackground) {
this.contextGrid.fillStyle = this.colorBackground;
this.contextGrid.fillRect(xDst, yDst, this.widthCell, this.heightCell);
} else {
this.contextGrid.clearRect(xDst, yDst, this.widthCell, this.heightCell);
}
}
/**
* drawBuffer(fForced, t)
*
* This is our periodic (60Hz) redraw function; however, it can also be called synchronously
* (eg, see clearBuffer()). The other important periodic side-effect of this function is clearing
* fBufferTickled, so that if no other setLEDState() calls occur between now and the next drawBuffer(),
* an automatic clearBuffer() will be triggered. This simulates the normal blanking of the display
* whenever the machine performs lengthy calculations, because for an LED display to remain lit,
* the machine must perform a display operation ("refresh") at least 30-60 times per second.
*
* @this {LED}
* @param {boolean} [fForced] (if not set, this is a normal refresh call)
* @param {number} [t] (time value, if available, from the requestAnimationFrame() callback)
*/
drawBuffer(fForced = false, t = 0)
{
if (this.fBufferModified || fForced) {
if (this.type < LED.TYPE.DIGIT) {
this.drawGrid(fForced);
} else {
let s = "";
for (let i = 0; i < this.buffer.length; i += this.nBufferInc) {
s += this.buffer[i] || ' ';
if (this.buffer[i+3] & LED.FLAGS.PERIOD) s += '.';
}
this.drawString(s);
}
this.fBufferModified = false;
this.iBufferRecent = -1;
}
else if (!this.fPersistent && !this.fBufferTickled) {
if (!t || !this.msLastDraw || (t - this.msLastDraw) >= ((1000 / 60)|0)) {
this.clearBuffer(true);
}
}
this.fBufferTickled = false;
if (t) this.msLastDraw = t;
}
/**
* drawGrid(fForced)
*
* Used by drawBuffer() for LED.TYPE.ROUND, LED.TYPE.SQUARE, etc.
*
* If the buffer was recently shifted left (ie, nShiftedLeft is set), then we take advantage
* of that knowledge to use drawImage() to shift the entire grid image left, and then redrawing
* only the rightmost visible column.
*
* @this {LED}
* @param {boolean} [fForced] (if not set, this is a normal refresh call)
*/
drawGrid(fForced)
{
let colRedraw = 0;
if (!this.fPersistent || fForced) {
this.clearGrid();
} else if (this.nShiftedLeft) {
colRedraw = this.colsView - this.nShiftedLeft;
let xStart = this.widthCell * this.nShiftedLeft;
let cxVisible = this.widthCell * colRedraw;
this.contextGrid.drawImage(this.canvasGrid, xStart, 0, cxVisible, this.heightGrid, 0, 0, cxVisible, this.heightGrid);
/*
* At this point, the only grid drawing we might need to do now is the column at colRedraw,
* but we still loop over the entire buffer to ensure all the cell MODIFIED states are in sync.
*/
}
let i = 0;
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.colsView; col++) {
let state = this.buffer[i];
let color = this.buffer[i+1] || this.colorTransparent;
let fLeaveModified = false;
let fModified = !!(this.buffer[i+3] & LED.FLAGS.MODIFIED);
let fHighlight = (this.fHighlight && i == this.iBufferRecent);
if (!this.fDisplayOn && state) {
state = LED.STATE.OFF;
fModified = fLeaveModified = true;
}
if (fModified || fHighlight || fForced) {
if (col >= colRedraw) {
this.drawGridCell(state, color, col, row, fHighlight);
}
if (fHighlight || fLeaveModified) {
this.buffer[i+3] |= LED.FLAGS.MODIFIED;
} else {
this.buffer[i+3] &= ~LED.FLAGS.MODIFIED;
}
}
i += this.nBufferInc;
}
i += this.nBufferIncExtra;
}
this.nShiftedLeft = 0;
this.drawView();
}
/**
* drawGridCell(state, color, col, row, fHighlight)
*
* Used by drawGrid() for LED.TYPE.ROUND, LED.TYPE.SQUARE, etc.
*
* @this {LED}
* @param {string} state (eg, LED.STATE.ON or LED.STATE.OFF)
* @param {string} [color]
* @param {number} [col] (default is zero)
* @param {number} [row] (default is zero)
* @param {boolean} [fHighlight] (true if the cell should be highlighted; default is false)
*/
drawGridCell(state, color, col = 0, row = 0, fHighlight = false)
{
let xOffset = 0;
if (this.fHexagonal) {
if (!(row & 0x1)) {
xOffset = (this.widthCell >> 1);
if (col == this.colsView - 1) return;
}
}
let colorOn, colorOff;
if (!color || color == this.colorOn) {
colorOn = fHighlight? this.colorHighlight : this.colorOn;
colorOff = this.colorOff;
} else {
colorOn = fHighlight? this.getRGBAColor(color, 1.0, 2.0) : color;
colorOff = this.getRGBAColor(color, 1.0, 0.25);
}
let fTransparent = false;
let colorCell = (state? colorOn : colorOff);
if (colorOn == this.colorTransparent) {
colorCell = this.colorBackground;
fTransparent = true;
}
let xDst = col * this.widthCell + xOffset;
let yDst = row * this.heightCell;
/*
* If this is NOT a persistent LED display, then drawGrid() will have done a preliminary clearGrid(),
* eliminating the need to clear individual cells. Whereas if this IS a persistent LED display, then
* we need to clear cells on an as-drawn basis. If we don't, there could be residual "bleed over"
* around the edges of the shape we drew here previously.
*/
if (this.fPersistent) {
this.clearGridCell(col, row, xOffset);
}
this.contextGrid.fillStyle = colorCell;
let coords = LED.SHAPES[this.type];
if (coords.length == 3) {
this.contextGrid.beginPath();
this.contextGrid.arc(xDst + coords[0], yDst + coords[1], coords[2], 0, Math.PI * 2);
if (fTransparent) {
/*
* The following code works as well:
*
* this.contextGrid.save();
* this.contextGrid.clip();
* this.contextGrid.clearRect(xDst, yDst, this.widthCell, this.heightCell);
* this.contextGrid.restore();
*
* but I assume it's not as efficient.
*/
this.contextGrid.globalCompositeOperation = "destination-out";
this.contextGrid.fill();
this.contextGrid.globalCompositeOperation = "source-over";
} else {
this.contextGrid.fill();
}
} else {
this.contextGrid.fillRect(xDst + coords[0], yDst + coords[1], coords[2], coords[3]);
}
}
/**
* drawGridSegment(seg, col, row)
*
* Used by drawSymbol() for LED.TYPE.DIGIT.
*
* @this {LED}
* @param {string} seg (eg, "A")
* @param {number} [col] (default is zero)
* @param {number} [row] (default is zero)
*/
drawGridSegment(seg, col = 0, row = 0)
{
let coords = LED.SEGMENTS[seg];
if (coords) {
let xDst = col * this.widthCell;
let yDst = row * this.heightCell;
this.contextGrid.fillStyle = this.colorOn;
this.contextGrid.beginPath();
if (coords.length == 3) {
this.contextGrid.arc(xDst + coords[0], yDst + coords[1], coords[2], 0, Math.PI * 2);
} else {
for (let i = 0; i < coords.length; i += 2) {
if (!i) {
this.contextGrid.moveTo(xDst + coords[i], yDst + coords[i+1]);
} else {
this.contextGrid.lineTo(xDst + coords[i], yDst + coords[i+1]);
}
}
}
this.contextGrid.closePath();
this.contextGrid.fill();
}
}
/**
* drawString(s)
*
* Used by drawBuffer() for LED.TYPE.DIGIT.
*
* @this {LED}
* @param {string} s
*/
drawString(s)
{
this.clearGrid();
for (let i = 0, col = 0, row = 0; i < s.length; i++) {
let ch = s[i];
if (ch == '.') {
if (col) col--;
}
this.drawSymbol(ch, col, row);
if (++col == this.colsView) {
col = 0;
if (++row == this.rows) {
break;
}
}
}
this.drawView();
}
/**
* drawSymbol(symbol, col, row)
*
* Used by drawString() for LED.TYPE.DIGIT.
*
* If the symbol does not exist in LED.SYMBOL_SEGMENTS, then nothing is drawn.
*
* @this {LED}
* @param {string} symbol
* @param {number} [col] (default is zero)
* @param {number} [row] (default is zero)
*/
drawSymbol(symbol, col = 0, row = 0)
{
let segments = LED.SYMBOL_SEGMENTS[symbol];
if (segments) {
for (let i = 0; i < segments.length; i++) {
this.drawGridSegment(segments[i], col, row)
}
}
}
/**
* drawView()
*
* @this {LED}
*/
drawView()
{
/*
* Setting the 'globalCompositeOperation' property of a 2D context is something you rarely need to do,
* because the default draw behavior ("source-over") is fine for most cases. One case where it is NOT
* fine is when we're using a transparent background color, because it doesn't copy over any transparent
* pixels, effectively making it impossible to "turn off" any previously drawn LED segments. To force
* that behavior, we must select the "copy" behavior.
*
* Refer to: https://www.w3.org/TR/2dcontext/#dom-context-2d-globalcompositeoperation
*/
this.contextView.globalCompositeOperation = (this.colorBackground && this.colorOn != this.colorTransparent)? "source-over" : "copy";
this.contextView.drawImage(this.canvasGrid, 0, 0, this.widthGrid, this.heightGrid, 0, 0, this.widthView, this.heightView);
}
/**
* enableDisplay(on)
*
* @this {LED}
* @param {boolean} [on]
*/
enableDisplay(on = true)
{
if (this.fDisplayOn != on) {
this.fDisplayOn = on;
this.fBufferModified = true;
}
}
/**
* getBuffer()
*
* @this {LED}
* @returns {Array}
*/
getBuffer()
{
return this.buffer;
}
/**
* getBufferClone()
*
* @this {LED}
* @returns {Array}
*/
getBufferClone()
{
if (!this.bufferClone) {
this.bufferClone = new Array(this.nBufferCells);
this.initBuffer(this.bufferClone);
}
return this.bufferClone;
}
/**
* getLEDColor(col, row)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @returns {string}
*/
getLEDColor(col, row)
{
let i = (row * this.cols + col) * this.nBufferInc;
return this.buffer[i+1] || this.colorTransparent;
}
/**
* getLEDColorValues(col, row, rgb)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @param {Array.<number>} rgb
* @returns {boolean}
*/
getLEDColorValues(col, row, rgb)
{
let i = (row * this.cols + col) * this.nBufferInc;
return this.parseRGBValues(this.buffer[i+1] || this.colorTransparent, rgb);
}
/**
* getLEDCounts(col, row, counts)
*
* This function returns success (true) ONLY for cells that are not transparent.
*
* For a typical "Lite-Brite" grid, transparent cells are considered "empty", so we want to
* ignore them.
*
* @this {LED}
* @param {number} col
* @param {number} row
* @param {Array.<number>} counts
* @returns {boolean}
*/
getLEDCounts(col, row, counts)
{
let fSuccess = false;
let i = (row * this.cols + col) * this.nBufferInc;
if (i <= this.buffer.length - this.nBufferInc && this.buffer[i+1]) {
fSuccess = true;
let bits = this.buffer[i+2];
for (let c = counts.length - 1; c >= 0; c--) {
counts[c] = bits & 0xf;
bits >>>= 4;
}
}
return fSuccess;
}
/**
* getLEDCountsPacked(col, row)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @returns {number}
*/
getLEDCountsPacked(col, row)
{
let i = (row * this.cols + col) * this.nBufferInc;
return (i <= this.buffer.length - this.nBufferInc)? this.buffer[i+2] : 0;
}
/**
* getLEDState(col, row)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @returns {number|undefined}
*/
getLEDState(col, row)
{
let state;
let i = (row * this.cols + col) * this.nBufferInc;
if (i <= this.buffer.length - this.nBufferInc) {
state = this.buffer[i];
}
return state;
}
/**
* getDefaultColor()
*
* @this {LED}
* @returns {string}
*/
getDefaultColor()
{
return this.colorOn;
}
/**
* getRGBColor(color, colorDefault)
*
* Returns a color string in the "hex" format that fillStyle recognizes (eg, "#rrggbb").
*
* The default is optional, allowing an undefined color to remain undefined if we want to use
* that to signal transparency (as in the case of colorBackground).
*
* @this {LED}
* @param {string|undefined} color
* @param {string} [colorDefault]
* @returns {string|undefined}
*/
getRGBColor(color, colorDefault)
{
color = color || colorDefault;
return color && WebIO.COLORS[color] || color;
}
/**
* getRGBColorString(rgb)
*
* Returns a color string fillStyle recognizes (ie, "#rrggbb", or "rgba(r,g,b,a)" if an alpha value
* less than 1 is set).
*
* TODO: Cache frequently requested colors.
*
* @this {LED}
* @param {Array.<number>} rgb
* @returns {string}
*/
getRGBColorString(rgb)
{
let s;
if (rgb.length < 4 || rgb[3] == 1) {
s = this.sprintf("#%02x%02x%02x", rgb[0], rgb[1], rgb[2]);
} else {
s = this.sprintf("rgba(%d,%d,%d,%d)", rgb[0], rgb[1], rgb[2], rgb[3]);
}
return s;
}
/**
* getRGBAColor(color, alpha, brightness)
*
* Returns a color string in the "rgba" format that fillStyle recognizes (eg, "rgba(255, 255, 255, 0)").
*
* I used to use "alpha" to adjust the brightness, but it's safer to use the "brightness" parameter,
* which simply scales all the RGB values. That's because if any shapes are redrawn using a fillStyle
* with alpha < 1.0, the target alpha values will be added instead of replaced, resulting in progressively
* brighter shapes; probably not what you want.
*
* @this {LED}
* @param {string} color
* @param {number} [alpha]
* @param {number} [brightness]
* @returns {string}
*/
getRGBAColor(color, alpha = 1.0, brightness = 1.0)
{
if (color) {
let rgb = [];
color = WebIO.COLORS[color] || color;
if (this.parseRGBValues(color, rgb)) {
color = "rgba(";
let i;
for (i = 0; i < 3; i++) {
let n = Math.round(rgb[i] * brightness);
n = (n < 0? 0 : (n > 255? 255 : n));
color += n + ",";
}
color += (i < rgb.length? rgb[i] : alpha) + ")";
}
}
return color;
}
/**
* initBuffer(buffer)
*
* @this {LED}
* @param {Array.<number|string|null>} buffer
*/
initBuffer(buffer)
{
for (let i = 0; i < buffer.length; i += this.nBufferInc) {
this.initCell(buffer, i);
}
}
/**
* initCell(buffer, iCell)
*
* @this {LED}
* @param {Array.<number|string|null>} buffer
* @param {number} iCell
*/
initCell(buffer, iCell)
{
if (this.type < LED.TYPE.DIGIT) {
buffer[iCell] = LED.STATE.OFF;
} else {
buffer[iCell] = ' ';
}
buffer[iCell+1] = (this.colorOn == this.colorTransparent? null : this.colorOn);
buffer[iCell+2] = 0;
buffer[iCell+3] = LED.FLAGS.MODIFIED;
}
/**
* loadState(state)
*
* If any saved values don't match (possibly overridden), abandon the given state and return false.
*
* @this {LED}
* @param {Array} state
* @returns {boolean}
*/
loadState(state)
{
let colorOn = state.shift();
let colorBackground = state.shift();
let buffer = state.shift();
if (colorOn == this.colorOn && colorBackground == this.colorBackground && buffer && buffer.length == this.buffer.length) {
this.buffer = buffer;
/*
* Loop over all the buffer colors to fix a legacy problem (ie, before we started storing null for colorTransparent)
*/
for (let i = 0; i <= this.buffer.length - this.nBufferInc; i += this.nBufferInc) {
if (this.buffer[i+1] == this.colorTransparent) this.buffer[i+1] = null;
}
this.drawBuffer(true);
return true;
}
return false;
}
/**
* parseRGBValues(color, rgb)
*
* @this {LED}
* @param {string} color
* @param {Array.<number>} rgb
* @returns {boolean}
*/
parseRGBValues(color, rgb)
{
let base = 16;
let match = color.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
if (!match) {
base = 10;
match = color.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,?\s*(\d+|)\)$/i);
}
if (match) {
let i;
for (i = 1; i < match.length; i++) {
rgb[i-1] = Number.parseInt(match[i], base);
}
rgb.length = i-1;
return true;
}
return false;
}
/**
* saveState(state)
*
* @this {LED}
* @param {Array} state
*/
saveState(state)
{
if (this.buffer) {
state.push(this.colorOn);
state.push(this.colorBackground);
state.push(this.buffer);
}
}
/**
* setContainerStyle(sAttr, sValue)
*
* @this {LED}
* @param {string} sAttr
* @param {string} sValue
*/
setContainerStyle(sAttr, sValue)
{
if (this.container) this.container.style[sAttr] = sValue;
}
/**
* setLEDColor(col, row, color)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @param {string} [color]
* @returns {boolean|null} (true if this call modified the LED color, false if not, null if error)
*/
setLEDColor(col, row, color)
{
let fModified = null;
if (row >= 0 && row < this.rows && col >= 0 && col < this.cols) {
fModified = false;
let colorNew = color || this.colorOn;
if (colorNew == this.colorTransparent) colorNew = null;
let i = (row * this.cols + col) * this.nBufferInc;
if (this.buffer[i+1] !== colorNew) {
this.buffer[i+1] = colorNew;
if (!colorNew) this.buffer[i] = LED.STATE.OFF; // transparent LEDs are automatically turned off
this.buffer[i+3] |= LED.FLAGS.MODIFIED;
this.fBufferModified = fModified = true;
}
this.iBufferRecent = i;
this.fBufferTickled = true;
}
return fModified;
}
/**
* setLEDCounts(col, row, counts)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @param {Array.<number>} counts
* @returns {boolean|null} (true if this call modified the LED color, false if not, null if error)
*/
setLEDCounts(col, row, counts)
{
let fModified = null;
if (row >= 0 && row < this.rows && col >= 0 && col < this.cols) {
fModified = false;
let i = (row * this.cols + col) * this.nBufferInc;
let bits = 0;
if (this.buffer[i+1]) { // only non-transparent LEDs are allowed to set counters
for (let c = 0; c < counts.length; c++) {
bits = (bits << 4) | (counts[c] & 0xf);
}
}
if (this.buffer[i+2] !== bits) {
this.buffer[i+2] = bits;
this.buffer[i+3] |= LED.FLAGS.MODIFIED;
this.fBufferModified = fModified = true;
}
this.iBufferRecent = i;
this.fBufferTickled = true;
}
return fModified;
}
/**
* setLEDCountsPacked(col, row, counts)
*
* @this {LED}
* @param {number} col
* @param {number} row
* @param {number} counts
* @returns {boolean|null} (true if this call modified the LED state, false if not, null if error)
*/
setLEDCountsPacked(col, row, counts)
{
let i = (row * this.cols + col) * this.nBufferInc;
if (i <= this.buffer.length - this.nBufferInc) {
if (this.buffer[i+2] != counts) {
this.buffer[i+2] = counts;
return true;
}
return false;
}
return null;
}
/**
* setLEDState(col, row, state, flags)
*
* For LED.TYPE.ROUND or LED.TYPE.SQUARE, the state parameter should be LED.STATE.OFF or LED.STATE.ON.
*
* @this {LED}