-
Notifications
You must be signed in to change notification settings - Fork 10
/
picture.js
1582 lines (1470 loc) · 59.2 KB
/
picture.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 Olli Etuaho 2012-2013.
*/
'use strict';
/**
* @constructor
* @param {number} id Picture's unique id number.
* @param {string} name Name of the picture. May be null.
* @param {Rect} boundsRect Picture bounds in picture coordinates. Left and top bounds may be negative.
* @param {number} bitmapScale Scale for rasterizing the picture. Events that
* are pushed to this picture get this scale applied to them.
* @param {PictureRenderer} renderer Renderer to use to draw the picture.
*/
var Picture = function(id, name, boundsRect, bitmapScale, renderer) {
this.id = id;
this.name = name;
this.renderer = renderer;
this.renderer.addRef();
this.parsedVersion = null;
this.freed = false; // Freed picture has no bitmaps. They can be regenerated.
this.animating = false;
this.activeSid = 0;
this.activeSessionEventId = 0;
this.lastSavedSessionEventId = 0;
this.buffers = []; // PictureBuffers
this.updates = []; // PictureUpdates (state changes used as the basis of serialization and animation).
this.currentEventAttachment = -1;
this.currentEvent = null;
this.currentEventUntilCoord = undefined;
this.currentEventMode = PictureEvent.Mode.normal;
this.currentEventColor = [255, 255, 255];
this.pictureTransform = new AffineTransform();
this.pictureTransform.scale = bitmapScale;
this.setBounds(boundsRect);
// Shouldn't use more GPU memory than this for buffers and rasterizers
// combined. Just guessing for a good generic limit, since WebGL won't give
// out an exact one. Assuming that 2D canvas elements count towards this.
this.memoryBudget = 256 * 1024 * 1024;
// Allocate space for the compositing buffer
this.memoryUse = this.bitmapWidth() * this.bitmapHeight() * 4;
this.container = null;
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
if (this.renderer.usesWebGl()) {
this.gl = this.renderer.gl;
this.glManager = this.renderer.glManager;
this.renderer.setPicture(this);
}
this.initRasterizers();
};
/**
* Add a PictureUpdate to this picture. This is the preferred way to interface with the Picture for applications which
* don't require inserting events to the middle of buffers. It enables serializing the picture and playing back an
* animation of its progress.
* @param {PictureUpdate} update The update to add.
* @param {boolean=} changeState Whether to change the state of the picture according to this update. Defaults to true,
* use false to keep the update stack consistent with the event data if you are using other functions to add/change
* events.
*/
Picture.prototype.pushUpdate = function(update, changeState) {
if (changeState === undefined) {
changeState = true;
}
if (changeState) {
if (update.updateType === 'undo') {
var undone = this.undoEventSessionId(update.undoneSid, update.undoneSessionEventId);
if (undone === null) {
console.log('pushUpdate: did not find the event to undo with session event id ' +
update.undoneSessionEventId);
return;
}
} else if (update.updateType === 'add_picture_event') {
this.pushEvent(update.targetLayerId, update.pictureEvent);
}
}
this.updates.push(update);
};
/**
* Set the bounds of the picture. Will resize the bitmaps, translating the existing bitmap contents to the right
* position and fill in any empty areas that might appear.
* @param {Rect} boundsRect Picture bounds in picture coordinates. Left and top bounds may be negative.
* @param {number=} bitmapScale Scale for the picture's bitmap. Will be clamped so that maximum framebuffer size limit
* is respected. Defaults to not changing the scale.
*/
Picture.prototype.crop = function(boundsRect, bitmapScale) {
if (bitmapScale === undefined) {
bitmapScale = this.pictureTransform.scale;
}
this.pictureTransform.scale = bitmapScale;
this.setBounds(boundsRect);
this.renderer.setPicture(this);
this.initRasterizers();
for (var i = 0; i < this.buffers.length; ++i) {
this.buffers[i].crop(this.bitmapRect.width(), this.bitmapRect.height(), this.renderer.sharedRasterizer);
}
};
/**
* Set the bounds of the picture. Sets pictureTransform to translate events to the bitmap coordinates. Will respect
* maximum framebuffer size.
* @param {Rect} boundsRect Picture bounds in picture coordinates. Left and top bounds may be negative.
* @protected
*/
Picture.prototype.setBounds = function(boundsRect) {
this.boundsRect = boundsRect;
if (this.pictureTransform.scale < this.minBitmapScale()) {
this.pictureTransform.scale = this.minBitmapScale();
}
if (this.pictureTransform.scale > this.maxBitmapScale()) {
this.pictureTransform.scale = this.maxBitmapScale();
}
this.pictureTransform.translate.x = -boundsRect.left * this.pictureTransform.scale;
this.pictureTransform.translate.y = -boundsRect.top * this.pictureTransform.scale;
++this.pictureTransform.generation;
var bitmapWidth = Math.floor(this.boundsRect.width() * this.pictureTransform.scale);
var bitmapHeight = Math.floor(this.boundsRect.height() * this.pictureTransform.scale);
this.bitmapRect = new Rect(0, bitmapWidth, 0, bitmapHeight);
};
/**
* @return {boolean} True if this picture hasn't changed since it last was
* marked as saved.
*/
Picture.prototype.hasBeenSaved = function() {
// TODO: Doesn't take undo into account. Maybe fix this.
return this.lastSavedSessionEventId === this.activeSessionEventId;
};
/**
* Mark this picture as saved.
*/
Picture.prototype.markAsSaved = function() {
this.lastSavedSessionEventId = this.activeSessionEventId;
};
/**
* Immediately remove reference to the renderer to free as many resources as possible.
* Meant mainly for testing.
*/
Picture.prototype.destroy = function() {
this.renderer.removeRef();
};
/**
* Add a buffer to the top of the buffer stack. Does the operation through pushUpdate.
* @param {number} id Identifier for this buffer. Unique at the Picture level.
* Should be an integer >= 0.
* @param {Array.<number>} clearColor 4-component array with RGBA color that's
* used to clear this buffer.
* @param {boolean} hasAlpha Does the buffer have an alpha channel?
*/
Picture.prototype.addBuffer = function(id, clearColor, hasAlpha) {
var addEvent = this.createBufferAddEvent(id, hasAlpha, clearColor);
var update = new PictureUpdate('add_picture_event');
update.setPictureEvent(id, addEvent);
this.pushUpdate(update);
};
/**
* Mark a buffer as removed from the stack. It won't be composited, but it can
* still be changed. Does the operation through pushUpdate.
* @param {number} id Identifier for the removed buffer.
*/
Picture.prototype.removeBuffer = function(id) {
var removeEvent = this.createBufferRemoveEvent(id);
var update = new PictureUpdate('add_picture_event');
update.setPictureEvent(id, removeEvent);
this.pushUpdate(update);
};
/**
* Move a buffer to the given index in the buffer stack. Current event stays
* attached to the moved buffer, if it exists. Does the operation through pushUpdate.
* @param {number} movedId The id of the buffer to move.
* @param {number} toIndex The index to move this buffer to. Must be an integer
* between 0 and Picture.buffers.length - 1.
*/
Picture.prototype.moveBuffer = function(movedId, toIndex) {
var moveEvent = this.createBufferMoveEvent(movedId, toIndex);
var update = new PictureUpdate('add_picture_event');
update.setPictureEvent(movedId, moveEvent);
this.pushUpdate(update);
};
/**
* Find a buffer with the given id from this picture.
* @param {Array.<PictureBuffer>} buffers Array to search for the buffer.
* @param {number} id Identifier of the buffer to find.
* @return {number} Index of the buffer or -1 if not found.
* @protected
*/
Picture.prototype.findBufferIndex = function(buffers, id) {
for (var i = 0; i < buffers.length; ++i) {
if (buffers[i].id === id) {
return i;
}
}
return -1;
};
/**
* Find a buffer with the given id from this picture.
* @param {number} id Identifier of the buffer to find.
* @return {PictureBuffer} Buffer or null if not found.
* @protected
*/
Picture.prototype.findBuffer = function(id) {
var ind = this.findBufferIndex(this.buffers, id);
if (ind !== -1) {
return this.buffers[ind];
}
return null;
};
/**
* Find the buffer that contains the given event.
* @param {PictureEvent} event The event to look for.
* @return {number} The buffer's id or -1 if not found.
*/
Picture.prototype.findBufferContainingEvent = function(event) {
for (var i = 0; i < this.buffers.length; ++i) {
if (this.buffers[i].eventIndexBySessionId(event.sid,
event.sessionEventId) >= 0) {
return this.buffers[i].id;
}
}
return -1;
};
/**
* @return {number} Id of the topmost composited buffer.
*/
Picture.prototype.topCompositedBufferId = function() {
var i = this.buffers.length;
while (i > 0) {
--i;
if (this.buffers[i].isComposited()) {
return this.buffers[i].id;
}
}
return -1;
};
/**
* Update the current event compositing mode and color.
* @protected
*/
Picture.prototype.updateCurrentEventMode = function() {
if (this.currentEvent !== null && this.currentEventAttachment >= 0) {
this.currentEventMode = this.currentEvent.mode;
this.currentEventColor = this.currentEvent.color;
var buffer = this.findBuffer(this.currentEventAttachment);
// TODO: assert(buffer !== null)
if (this.currentEventMode === PictureEvent.Mode.erase &&
!buffer.hasAlpha) {
this.currentEventMode = PictureEvent.Mode.normal;
this.currentEventColor = buffer.events[0].clearColor;
}
}
};
/**
* Attach the current event to the given buffer in the stack.
* @param {number} attachment Which buffer id to attach the picture's current
* event to. Can be set to -1 if no current event is needed.
*/
Picture.prototype.setCurrentEventAttachment = function(attachment) {
this.currentEventAttachment = attachment;
this.updateCurrentEventMode();
};
/**
* Set one of this picture's buffers visible or invisible.
* @param {number} bufferId The id of the buffer to adjust.
* @param {boolean} visible Is the buffer visible?
*/
Picture.prototype.setBufferVisible = function(bufferId, visible) {
this.findBuffer(bufferId).visible = visible;
};
/**
* Set the opacity of one of this picture's buffers.
* @param {number} bufferId The id of the buffer to adjust.
* @param {number} opacity Opacity value to set, range from 0 to 1.
*/
Picture.prototype.setBufferOpacity = function(bufferId, opacity) {
this.findBuffer(bufferId).events[0].opacity = opacity;
};
/**
* Create a picture object by parsing a serialization of it. Note that the
* picture might not be immediately ready after parsing, but might instead be
* freed when this function returns and take a while to load imported bitmaps,
* after which the picture will be regenerated for display.
* TODO: Make returning the picture asynchronous?
* @param {number} id Unique identifier for the picture.
* @param {string} serialization Serialization of the picture as generated by
* Picture.prototype.serialize(). May optionally have metadata not handled by
* the Picture object at the end, separated by line "metadata".
* @param {number} bitmapScale Scale for rasterizing the picture. Events that
* are pushed to this picture get this scale applied to them.
* @param {PictureRenderer} renderer Renderer to use to draw the picture.
* @param {function(Object)} finishedCallback Function to be called asynchronously when loading has finished.
* The function will be called with one parameter, an object containing key 'picture' for the created picture,
* and key 'metadata' for the metadata lines.
*/
Picture.parse = function(id, serialization, bitmapScale, renderer, finishedCallback) {
var eventStrings = serialization.split(/\r?\n/);
var pictureParams = eventStrings[0].split(' ');
var version = 0;
var left = 0;
var top = 0;
var width = 0;
var height = 0;
var name = null;
if (pictureParams[1] !== 'version') {
width = parseInt(pictureParams[1]);
height = parseInt(pictureParams[2]);
} else {
version = parseInt(pictureParams[2]);
if (version < 6) {
width = parseInt(pictureParams[3]);
height = parseInt(pictureParams[4]);
} else {
left = parseFloat(pictureParams[3]);
top = parseFloat(pictureParams[4]);
width = parseFloat(pictureParams[5]);
height = parseFloat(pictureParams[6]);
}
}
if (version > 2) {
var nameIndex = 5;
if (version > 5) {
nameIndex = 7;
}
var hasName = pictureParams[nameIndex];
if (hasName === 'named') {
name = window.atob(pictureParams[nameIndex + 1]);
}
}
var pic = new Picture(id, name, new Rect(left, left + width, top, top + height), bitmapScale, renderer);
pic.parsedVersion = version;
// First parse all buffers without rasterizing, then rasterize after rasterImport events are loaded.
pic.freed = true;
var i = 1;
var rasterImportEvents = [];
var generateUpdates = function() {
// Reconstruct a chain of PictureUpdates that will result in the parsed picture.
var buffersPushed = [];
var pushedBufferUpdates = function(buf) {
for (var k = 0; k < buffersPushed.length; ++k) {
if (buffersPushed[k] === buf.id) {
return true;
}
}
return false;
};
var pushBufferUpdates = function(buf) {
buffersPushed.push(buf.id);
for (var k = 0; k < buf.events.length; ++k) {
var event = buf.events[k];
if (event.eventType === 'bufferMerge' && !pushedBufferUpdates(event.mergedBuffer)) {
pushBufferUpdates(event.mergedBuffer);
}
var update = new PictureUpdate('add_picture_event');
update.setPictureEvent(buf.id, event);
pic.pushUpdate(update, false);
if (event.undone) {
var undoUpdate = new PictureUpdate('undo');
undoUpdate.setUndoEvent(event.sid, event.sessionEventId);
pic.pushUpdate(undoUpdate, false);
}
}
};
for (var j = 0; j < pic.buffers.length; ++j) {
if (!pic.buffers[j].isMerged()) {
pushBufferUpdates(pic.buffers[j]);
}
}
};
var regenerateIfReady = function() {
var ready = true;
for (i = 0; i < rasterImportEvents.length; ++i) {
if (!rasterImportEvents[i].loaded) {
ready = false;
}
}
if (ready) {
pic.regenerate();
if (version < 5) {
generateUpdates();
}
finishedCallback({picture: pic, metadata: metadata});
} else {
setTimeout(regenerateIfReady, 10);
}
};
if (version < 5) {
// Parse events, old style.
pic.moveBufferInternal = function() {}; // Move events can be processed out
// of order here, so we don't apply them. Instead rely on buffers being
// already in the correct order.
var currentId = -1;
var mergeEvents = [];
while (i < eventStrings.length) {
if (eventStrings[i] === 'metadata') {
break;
} else {
var arr = eventStrings[i].split(' ');
var json = {};
PictureEvent.parseLegacy(json, arr, 0, version);
var pictureEvent = PictureEvent.fromJS(json);
if (pictureEvent.eventType === 'bufferMerge') {
mergeEvents.push(pictureEvent);
}
if (pictureEvent.eventType === 'rasterImport') {
rasterImportEvents.push(pictureEvent);
}
pic.pushEvent(currentId, pictureEvent);
currentId = pic.buffers[pic.buffers.length - 1].id;
++i;
}
}
// Merged buffer might not have been present when the merge target buffer was parsed.
// This will only set mergedBuffer on the events.
// mergedTo will be set on buffers when the picture is regenerated.
for (var j = 0; j < mergeEvents.length; ++j) {
pic.undummify(mergeEvents[j]);
}
delete pic.moveBufferInternal; // switch back to prototype's move function
} else {
// Parse PictureUpdates and process them in the original order.
var json;
while (i < eventStrings.length) {
if (eventStrings[i] === 'metadata') {
break;
} else {
if (version < 7) {
json = PictureUpdate.parseLegacy(eventStrings[i], version);
} else {
json = JSON.parse(eventStrings[i]);
}
var update = PictureUpdate.fromJS(json);
if (update.updateType === 'add_picture_event' &&
update.pictureEvent.eventType === 'rasterImport') {
rasterImportEvents.push(update.pictureEvent);
}
pic.pushUpdate(update);
++i;
}
}
}
var metadata = [];
if (i < eventStrings.length && eventStrings[i] === 'metadata') {
metadata = eventStrings.slice(i);
}
for (i = 0; i < pic.buffers.length; ++i) {
pic.buffers[i].insertionPoint = pic.buffers[i].events[0].insertionPoint;
}
setTimeout(regenerateIfReady, 0);
};
/**
* Create a copy of the given picture. You may optionally scale the picture at
* the same time.
* @param {Picture} pic The picture to copy.
* @param {function(Picture)} finishedCallback Function that will be called
* asynchronously with the copy once copying is done.
* @param {number=} bitmapScale The scale to set to the new picture. The new
* picture's bitmap width will be the old picture's width() * bitmapScale.
* Defaults to keeping the current scale.
*/
Picture.copy = function(pic, finishedCallback, bitmapScale) {
if (bitmapScale === undefined) {
bitmapScale = pic.pictureTransform.scale;
}
var serialization = pic.serialize();
Picture.parse(pic.id, serialization, bitmapScale,
pic.renderer, function(parsed) {
parsed.picture.setCurrentEventAttachment(pic.currentEventAttachment);
finishedCallback(parsed.picture);
});
};
/**
* @return {number} The maximum scale to which this picture can be reliably
* resized on the current configuration.
*/
Picture.prototype.maxBitmapScale = function() {
// Note: if WebGL is unsupported, falls back to default (unconfirmed)
// glUtils.maxFramebufferSize. This is a reasonable value for 2D canvas.
return glUtils.maxFramebufferSize / Math.max(this.width(), this.height());
};
/**
* @return {number} The minimum scale to which this picture can be reliably
* resized on the current configuration.
*/
Picture.prototype.minBitmapScale = function() {
return BaseRasterizer.minSize / Math.min(this.width(), this.height()) * 1.0001;
};
/** @const */
Picture.formatVersion = 7;
/**
* @return {string} A serialization of this Picture. Can be parsed into a new
* Picture by calling Picture.parse. Compatibility is guaranteed between at
* least two subsequent versions.
*/
Picture.prototype.serialize = function() {
var formatVersion = Picture.formatVersion;
var nameSerialization = this.name === null ? 'unnamed' : 'named ' + window.btoa(this.name);
var serialization = ['picture version ' + formatVersion + ' ' +
this.boundsRect.left + ' ' + this.boundsRect.top + ' ' +
this.width() + ' ' + this.height() + ' ' +
nameSerialization];
for (var i = 0; i < this.buffers.length; ++i) {
var buffer = this.buffers[i];
buffer.events[0].insertionPoint = buffer.insertionPoint;
}
for (var i = 0; i < this.updates.length; ++i) {
serialization.push(serializeToString(this.updates[i]));
}
return serialization.join('\n');
};
/**
* @return {number} The total event count in all buffers, undone or not.
*/
Picture.prototype.getEventCount = function() {
var count = 0;
for (var i = 0; i < this.buffers.length; ++i) {
count += this.buffers[i].events.length;
}
return count;
};
/**
* Set the session with the given sid active for purposes of createBrushEvent,
* createScatterEvent, createGradientEvent, createRasterImportEvent, createMergeEvent,
* createBufferAddEvent, addBuffer, createBufferRemoveEvent,
* createBufferMoveEvent, removeBuffer and undoLatest.
* @param {number} sid The session id to activate. Must be a positive integer.
*/
Picture.prototype.setActiveSession = function(sid) {
this.activeSid = sid;
this.activeSessionEventId = 0;
var latest = this.findLatest(sid, true);
if (latest !== null) {
this.activeSessionEventId = latest.sessionEventId + 1;
}
};
/**
* Create a brush event using the current active session. The event is marked as
* not undone.
* @param {Uint8Array|Array.<number>} color The RGB color of the stroke. Channel
* values are between 0-255.
* @param {number} flow Alpha value controlling blending individual brush
* samples (circles) to each other in the rasterizer. Range 0 to 1. Normalized
* to represent the resulting maximum alpha value in the rasterizer's bitmap in
* case of a straight stroke and the maximum pressure.
* @param {number} opacity Alpha value controlling blending the rasterizer
* stroke to the target buffer. Range 0 to 1.
* @param {number} radius The stroke radius in pixels.
* @param {number} textureId Id of the brush tip shape texture. 0 is a circle, others are bitmap textures.
* @param {number} softness Value controlling the softness. Range 0 to 1. Only applies to circles.
* @param {PictureEvent.Mode} mode Blending mode to use.
* @return {BrushEvent} The created brush event.
*/
Picture.prototype.createBrushEvent = function(color, flow, opacity, radius,
textureId, softness, mode) {
var event = new BrushEvent();
event.init(this.activeSid, this.activeSessionEventId, false,
color, flow, opacity, radius, textureId, softness, mode);
this.activeSessionEventId++;
return event;
};
/**
* Create a scatter event using the current active session. The event is marked
* as not undone.
* @param {Uint8Array|Array.<number>} color The RGB color of the event. Channel
* values are between 0-255.
* @param {number} flow Alpha value controlling blending individual brush
* samples (circles) to each other in the rasterizer. Range 0 to 1.
* @param {number} opacity Alpha value controlling blending the rasterizer data
* to the target buffer. Range 0 to 1.
* @param {number} radius The circle radius in pixels.
* @param {number} textureId Id of the brush tip shape texture. 0 is a circle, others are bitmap textures.
* @param {number} softness Value controlling the softness. Range 0 to 1. Only applies to circles.
* @param {PictureEvent.Mode} mode Blending mode to use.
* @return {ScatterEvent} The created scatter event.
*/
Picture.prototype.createScatterEvent = function(color, flow, opacity, radius,
textureId, softness, mode) {
var event = new ScatterEvent();
event.init(this.activeSid, this.activeSessionEventId,
false, color, flow, opacity, radius, textureId, softness, mode);
this.activeSessionEventId++;
return event;
};
/**
* Create a gradient event using the current active session. The event is marked
* as not undone.
* @param {Uint8Array|Array.<number>} color The RGB color of the gradient.
* Channel values are between 0-255.
* @param {number} opacity Alpha value controlling blending the rasterized
* gradient to the target buffer. Range 0 to 1.
* @param {PictureEvent.Mode} mode Blending mode to use.
* @return {GradientEvent} The created gradient event.
*/
Picture.prototype.createGradientEvent = function(color, opacity, mode) {
var event = new GradientEvent(this.activeSid, this.activeSessionEventId,
false, color, opacity, mode);
this.activeSessionEventId++;
return event;
};
/**
* Create a raster import event using the current active session. The event is
* marked as not undone.
* @param {HTMLImageElement} importedImage The imported image.
* @param {Rect} rect Rectangle defining the position and scale of the imported image in the buffer.
* @return {RasterImportEvent} The created raster import event.
*/
Picture.prototype.createRasterImportEvent = function(importedImage, rect) {
var event = new RasterImportEvent(this.activeSid, this.activeSessionEventId, false, importedImage, rect);
this.activeSessionEventId++;
return event;
};
/**
* Create a buffer add event using the current active session. The event is
* marked as not undone.
* @param {number} id Id of the added buffer. Unique at the Picture level.
* @param {boolean} hasAlpha Whether the buffer has an alpha channel.
* @param {Uint8Array|Array.<number>} clearColor The RGB(A) color used to clear
* the buffer. Channel values are integers between 0-255.
* @return {BufferAddEvent} The created buffer adding event.
*/
Picture.prototype.createBufferAddEvent = function(id, hasAlpha, clearColor) {
var createEvent = new BufferAddEvent(this.activeSid,
this.activeSessionEventId, false, id,
hasAlpha, clearColor, 1.0, 0);
this.activeSessionEventId++;
return createEvent;
};
/**
* Create a buffer removal event using the current active session. The event is
* marked as not undone.
* @param {number} id Id of the removed buffer.
* @return {BufferRemoveEvent} The created buffer adding event.
*/
Picture.prototype.createBufferRemoveEvent = function(id) {
// TODO: assert(this.findBufferIndex(this.buffers, id) >= 0);
var removeEvent = new BufferRemoveEvent(this.activeSid,
this.activeSessionEventId, false,
id);
this.activeSessionEventId++;
return removeEvent;
};
/**
* Create a buffer move event using the current active session. The event is
* marked as not undone.
* @param {number} movedId Id of the moved buffer.
* @param {number} toIndex Index to move the buffer to.
* @return {BufferMoveEvent} The created buffer move event.
*/
Picture.prototype.createBufferMoveEvent = function(movedId, toIndex) {
var fromIndex = this.findBufferIndex(this.buffers, movedId);
// TODO: assert(fromIndex >= 0);
var moveEvent = new BufferMoveEvent(this.activeSid,
this.activeSessionEventId, false,
movedId, fromIndex, toIndex);
this.activeSessionEventId++;
return moveEvent;
};
/**
* Create a merge event merging a buffer to the one below.
* @param {number} mergedBufferIndex The index of the top buffer that will be
* merged. The buffer must not be already merged.
* @param {number} opacity Alpha value controlling blending the top buffer.
* Range 0 to 1.
* @return {BufferMergeEvent} The created merge event.
*/
Picture.prototype.createMergeEvent = function(mergedBufferIndex, opacity) {
// TODO: assert(mergedBufferIndex >= 0);
var event = new BufferMergeEvent(this.activeSid, this.activeSessionEventId,
false, opacity,
this.buffers[mergedBufferIndex]);
this.activeSessionEventId++;
return event;
};
/**
* Create an event that hides the specified event.
* @param {number} hiddenSid The session identifier of the hidden event.
* @param {number} hiddenSessionEventId Event/session specific identifier of the
* hidden event.
* @return {EventHideEvent} The created hide event.
*/
Picture.prototype.createEventHideEvent = function(hiddenSid,
hiddenSessionEventId) {
var event = new EventHideEvent(this.activeSid, this.activeSessionEventId,
false, hiddenSid, hiddenSessionEventId);
this.activeSessionEventId++;
return event;
};
/**
* Set a containing widget for this picture. The container is expected to add
* what's returned from pictureElement() under a displayed HTML element.
* @param {Object} container The container.
*/
Picture.prototype.setContainer = function(container) {
this.container = container;
};
/**
* @return {HTMLCanvasElement} the element that displays the rasterized picture.
*/
Picture.prototype.pictureElement = function() {
return this.canvas;
};
/**
* Initialize rasterizers.
* @protected
*/
Picture.prototype.initRasterizers = function() {
this.renderer.setSharedRasterizerSize(this.bitmapWidth(), this.bitmapHeight());
};
/**
* @param {GLBuffer|CanvasBuffer} buffer The buffer to consider.
* @return {number} The priority for selecting this buffer for reducing memory
* budget. Higher priority means that the buffer's memory is more likely to be
* reduced.
*/
Picture.prototype.bufferFreeingPriority = function(buffer) {
var priority = buffer.undoStateBudget;
if ((buffer.isRemoved() || buffer.isMerged()) &&
buffer.undoStateBudget > 1) {
priority += buffer.undoStateBudget - 1.5;
}
priority -= buffer.undoStates.length * 0.1;
// TODO: Spice this up with a LRU scheme?
return priority;
};
/**
* Attempt to stay within the given memory budget.
* @param {number} requestedFreeBytes how much space to leave free.
*/
Picture.prototype.stayWithinMemoryBudget = function(requestedFreeBytes) {
var available = this.memoryBudget - requestedFreeBytes;
var needToFree = this.memoryUse - available;
var freeingPossible = true;
while (needToFree > 0 && freeingPossible) {
freeingPossible = false;
var selectedBuffer = null;
var selectedPriority = 0;
var i;
for (i = 0; i < this.buffers.length; ++i) {
if (this.buffers[i].undoStateBudget > 1 && !this.buffers[i].freed) {
freeingPossible = true;
var priority = this.bufferFreeingPriority(this.buffers[i]);
if (priority > selectedPriority) {
selectedBuffer = this.buffers[i];
selectedPriority = priority;
}
}
}
if (selectedBuffer !== null) {
var newBudget = selectedBuffer.undoStateBudget - 1;
selectedBuffer.setUndoStateBudget(newBudget);
this.memoryUse -= selectedBuffer.getStateMemoryBytes();
}
needToFree = this.memoryUse - available;
}
return;
};
/**
* @return {number} The average undo state budget of buffers that are not
* removed or merged.
*/
Picture.prototype.averageUndoStateBudgetOfActiveBuffers = function() {
var n = 0;
var sum = 0;
for (var i = 0; i < this.buffers.length; ++i) {
if (!this.buffers[i].isRemoved()) {
sum += this.buffers[i].undoStateBudget;
++n;
}
}
if (n > 0) {
return sum / n;
} else {
return 5;
}
};
/**
* Free a buffer and do the related memory accounting. Can be called on a buffer
* that is already freed, in which case the function has no effect.
* @param {CanvasBuffer|GLBuffer} buffer Buffer to regenerate.
* @protected
*/
Picture.prototype.freeBuffer = function(buffer) {
if (!buffer.freed) {
buffer.free();
this.memoryUse -= buffer.getMemoryNeededForReservingStates();
}
};
/**
* Regenerate a buffer and do the related memory accounting. Can be called on a
* buffer that is not freed, in which case the function has no effect.
* @param {CanvasBuffer|GLBuffer} buffer Buffer to regenerate.
* @protected
*/
Picture.prototype.regenerateBuffer = function(buffer) {
if (buffer.freed) {
var memIncrease = buffer.getMemoryNeededForReservingStates();
this.stayWithinMemoryBudget(memIncrease);
buffer.regenerate(true, this.renderer.sharedRasterizer);
this.memoryUse += memIncrease;
}
};
/**
* Create a single buffer using the mode specified for this picture.
* @param {BufferAddEvent} createEvent Event that initializes the buffer.
* @param {boolean} hasUndoStates Does the buffer store undo states?
* @return {GLBuffer|CanvasBuffer} The buffer.
* @protected
*/
Picture.prototype.createBuffer = function(createEvent, hasUndoStates) {
var buffer;
if (this.renderer.usesWebGl()) {
buffer = new GLBuffer(this.gl, this.glManager, this.renderer.compositor,
this.renderer.texBlitProgram, this.renderer.rectBlitProgram, createEvent,
this.bitmapWidth(), this.bitmapHeight(), this.pictureTransform,
hasUndoStates, this.freed);
} else {
// TODO: assert(this.renderer.mode === 'canvas');
buffer = new CanvasBuffer(createEvent, this.bitmapWidth(),
this.bitmapHeight(), this.pictureTransform, hasUndoStates, this.freed);
}
if (hasUndoStates) {
if (buffer.events[0].undone) {
var avgBudget = this.averageUndoStateBudgetOfActiveBuffers();
buffer.setUndoStateBudget(avgBudget);
return buffer;
}
// Buffers always store their current state
this.memoryUse += buffer.getStateMemoryBytes();
var avgBudget = this.averageUndoStateBudgetOfActiveBuffers();
avgBudget = Math.floor(avgBudget);
// Request free space for current average amount of undo states.
this.stayWithinMemoryBudget(buffer.getStateMemoryBytes() * avgBudget);
var spaceLeftStates = Math.floor((this.memoryBudget - this.memoryUse) /
buffer.getStateMemoryBytes());
if (spaceLeftStates < 0) {
console.log('Running out of GPU memory, budget set at ' +
(this.memoryBudget / (1024 * 1024)) + ' MB');
spaceLeftStates = 0;
}
if (spaceLeftStates > 5) {
spaceLeftStates = 5; // More is a waste for a new buffer
}
buffer.setUndoStateBudget(spaceLeftStates);
this.memoryUse += spaceLeftStates * buffer.getStateMemoryBytes();
if (false) { // Debug logging
console.log('Undo state budgets');
for (var i = 0; i < this.buffers.length; ++i) {
console.log(this.buffers[i].undoStateBudget);
}
console.log(buffer.undoStateBudget);
console.log('GPU memory use ' +
(this.memoryUse / (1024 * 1024)) + ' MB');
}
}
return buffer;
};
/**
* @return {number} The rasterizer bitmap width of the picture in pixels.
*/
Picture.prototype.bitmapWidth = function() {
return this.bitmapRect.width();
};
/**
* @return {number} The rasterizer bitmap height of the picture in pixels.
*/
Picture.prototype.bitmapHeight = function() {
return this.bitmapRect.height();
};
/**
* @return {number} The width of the picture's current bounds.
*/
Picture.prototype.width = function() {
return this.boundsRect.width();
};
/**
* @return {number} The height of the picture's current bounds.
*/
Picture.prototype.height = function() {
return this.boundsRect.height();
};
/**
* Do memory management after adding/redoing a remove event to a buffer.
* @param {PictureBuffer} buffer The buffer that the remove event was applied
* to. The event is allowed to be undone, which can cause the buffer to be not
* actually removed.
* @protected
*/
Picture.prototype.afterRemove = function(buffer) {
if (buffer.events.length < buffer.undoStateInterval * 2 &&
buffer.isRemoved()) {
// The buffer's bitmap isn't very costly to regenerate, so it
// can be freed.
this.freeBuffer(buffer);
}
};
/**
* Add an event to the top of one of this picture's buffers. Using this
* directly requires that you also add the same event through pushUpdate,
* otherwise you can not use serialization or animation functionality.
* @param {number} targetBufferId The id of the buffer to apply the event to. In
* case the event is a buffer add event, the id is ignored.
* @param {PictureEvent} event Event to add.
*/
Picture.prototype.pushEvent = function(targetBufferId, event) {
if (event.isBufferStackChange()) {
if (event.eventType === 'bufferAdd') {
var buffer = this.createBuffer(event, true);
this.buffers.push(buffer);
return;
} else if (event.eventType === 'bufferRemove') {
var bufferIndex = this.findBufferIndex(this.buffers,
event.bufferId);
// TODO: assert(bufferIndex >= 0);
this.buffers[bufferIndex].pushEvent(event, this.renderer.sharedRasterizer);
this.afterRemove(this.buffers[bufferIndex]);
return;
} else if (event.eventType === 'bufferMove') {
var fromIndex = this.findBufferIndex(this.buffers, event.movedId);
this.buffers[fromIndex].pushEvent(event);
if (!event.undone) {
this.moveBufferInternal(fromIndex, event.toIndex);
}
return;
}
}
var targetBuffer = this.findBuffer(targetBufferId);
if (this.renderer.currentEventRasterizer.drawEvent === event) {
targetBuffer.pushEvent(event, this.renderer.currentEventRasterizer);