forked from predixdesignsystem/px-vis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
px-vis-behavior-renderer.html
838 lines (718 loc) · 27.2 KB
/
px-vis-behavior-renderer.html
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
<!--
Copyright (c) 2018, General Electric
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="import" href="px-vis-behavior-common.html">
<link rel="import" href="px-vis-behavior-d3.html">
<script>
var PxVisBehaviorRenderer = window.PxVisBehaviorRenderer = (window.PxVisBehaviorRenderer || {});
/*
Name:
PxVisBehaviorRenderer.debounceOnPanning
Description:
Polymer behavior that provides ability to control debouncing on panning
Dependencies:
- none
@polymerBehavior PxVisBehaviorRenderer.debounceOnPanning
*/
PxVisBehaviorRenderer.debounceOnPanning = {
properties: {
/**
* Debounce time to use for different types of rendering
*/
drawDebounceTime: {
type: Object,
value: function() {
return {
'chartData': 10,
'filteredChartData': 10,
'highlightData': 10,
'markers': 10
};
}
},
_oldDrawDebounceTime: {
type: Object
},
/**
* Whether the drawings will be debounced on panning the chart.
* When not debounced the redraw will happen more often on panning,
* which should result in a smoother experience. However if rendering
* a big number of points this can have the opposite effect since
* it wil redraw too often comapred tot he time taken to re render everything
*/
debounceOnPanning: {
type: Boolean,
value: false
}
},
attached: function() {
this.listen(this, 'px-vis-interaction-space-start-panning', '_panningStarted');
this.listen(this, 'px-vis-interaction-space-stop-panning', '_panningStopped');
},
detached: function() {
this.unlisten(this, 'px-vis-interaction-space-start-panning', '_panningStarted');
this.unlisten(this, 'px-vis-interaction-space-stop-panning', '_panningStopped');
},
_panningStarted: function() {
if(!this.debounceOnPanning) {
this._oldDrawDebounceTime = this.drawDebounceTime;
this.drawDebounceTime = {
'chartData': 0,
'filteredChartData': 0,
'highlightData': this._oldDrawDebounceTime.highlightData,
'markers': 0
};
}
},
_panningStopped: function() {
if(!this.debounceOnPanning) {
this.drawDebounceTime = this._oldDrawDebounceTime;
}
}
};
/*
Name:
PxVisBehaviorRenderer.base
Description:
Polymer behavior that provides
Dependencies:
- none
@polymerBehavior PxVisBehaviorRenderer.base
*/
PxVisBehaviorRenderer.base = [{
/**
* px-vis-chart-canvas-rendering-started, fired when a chart starts rendering
* some data on a canvas. This can be a highlighter, actual chart data or some
* markers.
* evt.details contains a `context` which is used internally to define what
* should be rendered. Interesting properties of this context are:
* - renderType: what type of rendering is occuring (chartData, markers, highlightData, filteredChartData)
* - canvasToClear: array of the canvases that will be cleared before drawing
* - canvasTargets: array of targets that will be rendered (e.g px-vis-line-canvas)
*
* @event px-vis-chart-canvas-rendering-started
*/
/**
* px-vis-chart-canvas-rendering-ended, fired when a chart is done rendering
* some data on a canvas. This can be a highlighter, actual chart data or some
* markers.
* evt.details contains a `context` which is used internally to define what
* has been rendered. Interesting properties of this context are:
* - renderType: what type of rendering is occuring (chartData, markers, highlightData, filteredChartData)
* - canvasToClear: array of the canvases that will be cleared before drawing
* - canvasTargets: array of targets that will be rendered (e.g px-vis-line-canvas)
* - frameIndex: how many frames it took to render
*
* @event px-vis-chart-canvas-rendering-ended
*/
properties: {
/**
* Counter to track progressive rendering requests and only draw the latest one
*/
_progressiveRenderingCounter: {
type: Object,
value: function() {
return this._initializeRendererTypeObject(0);
}
},
/**
* Current registered targets to draw on canvas during rendering
*/
_canvasTargets: {
type: Object,
value: function() {
return this._initializeRendererTypeObject([]);
}
},
/**
* Current registered targets to draw on svg during rendering
*/
_svgTargets: {
type: Object,
value: function() {
return this._initializeRendererTypeObject([]);
}
},
/**
* The minimum number of points to render per frame
* even if the chart is laggy
*/
rendererMinimumPointsPerFrame: {
type: Number,
value: 50
},
/**
* Target duration (in ms) for one frame. The renderer will try to render
* as much data as possible in that given timeframe before calling the next
* animation frame.
* WARNING: this needs to be higher than 16ms since by default
* requestAnimationFrame will be called every ~16ms, so our target needs to
* be higher to ensure we keep the processor busy
*/
rendererFrameDurationTarget: {
type: Number,
value: 20
},
_internalRendererFrameDurationTarget: {
type: Number,
value: 20
},
/**
* Number of previous frames to average for the adaptive
* progressive rendering
*/
rendererFrameCountToAverage: {
type: Number,
value: 3
},
/**
* For each renderer type the previous frames number of points and duration for line and scatter
*/
_previousFramesTiming: {
type: Object,
value: function() {
return this._initializeRendererTypeObject({
'line': [],
'scatter': [],
'cell': []
});
}
},
_hasBeenDetached: {
type: Boolean,
value: false
}
},
observers: [
'_targetTimingChanged(rendererFrameDurationTarget)'
],
created: function() {
this.listen(this, 'px-vis-renderer-register', '_registerDrawingElement');
this.listen(this, 'px-vis-renderer-update-target-props', '_updateTargetProperty');
},
attached: function() {
this.listen(this, 'px-vis-highlight-data-changed', '_renderHighlight');
this.listen(this, 'px-vis-redraw-lines', '_renderAllLines');
//ensure we redraw
if(this._hasBeenDetached) {
//give some time for the elemnts to re register :(
window.setTimeout(function() {
this._renderChartData();
this._renderFilteredChartData();
this._renderMarkers();
this._renderHighlight();
}.bind(this), 50);
}
},
detached: function() {
//reset counter so it cancels current drawing
this._progressiveRenderingCounter = this._initializeRendererTypeObject(0);
this.unlisten(this, 'px-vis-highlight-data-changed', '_renderHighlight');
this.unlisten(this, 'px-vis-redraw-lines', '_renderAllLines');
this._hasBeenDetached = true;
},
/**
* Creates an object with all renderer types and a default value for each
*/
_initializeRendererTypeObject: function(initialVal) {
//make sure the values are not linked
return {
'chartData': initialVal,
'filteredChartData': JSON.parse(JSON.stringify(initialVal)),
'highlightData': JSON.parse(JSON.stringify(initialVal)),
'markers': JSON.parse(JSON.stringify(initialVal))
}
},
_updateTargetProperty: function(e) {
var propName = e.detail.propertyName,
val = e.detail.propertyValue,
target = Polymer.dom(e).rootTarget,
renderType = e.detail.rendererType,
current;
for(var i=0; i<this._canvasTargets[renderType].length; i++) {
current = this._canvasTargets[renderType][i];
if(current.target === target) {
current[propName] = val;
}
}
e.stopPropagation();
},
/**
* Elements wanting to use the renderer need to fire an event which
* will be processed here
*/
_registerDrawingElement: function(e) {
var evt = Polymer.dom(e);
if(e.detail.renderMode === 'canvas') {
this._canvasTargets[e.detail.rendererType].push({'target': evt.rootTarget, 'type': e.detail.type, 'priority': e.detail.priority});
} else {
this._svgTargets[e.detail.rendererType].push({'target': evt.rootTarget, 'type': e.detail.type});
}
this.listen(evt.rootTarget, 'px-vis-renderer-unregister', '_unregisterDrawingElement');
e.stopPropagation();
},
/**
* Elements wanting to use the renderer need to fire an event (on detached)
* which will be processed here
*/
_unregisterDrawingElement: function(e) {
var evt = Polymer.dom(e),
index = -1;
if(e.detail.renderMode === 'canvas') {
for(var i=0; i<this._canvasTargets[e.detail.rendererType].length; i++) {
if(evt.rootTarget === this._canvasTargets[e.detail.rendererType][i].target) {
index = i;
break;
}
}
if(i !== -1) {
this._canvasTargets[e.detail.rendererType].splice(i,1);
}
} else {
for(var i=0; i<this._svgTargets[e.detail.rendererType].length; i++) {
if(evt.rootTarget === this._svgTargets[e.detail.rendererType][i].target) {
index = i;
break;
}
}
if(i !== -1) {
this._svgTargets[e.detail.renderType].splice(i,1);
}
}
this.unlisten(evt.rootTarget, 'px-vis-renderer-unregister', '_unregisterDrawingElement');
e.stopPropagation();
},
/*****************************************************************
* Handlers for starting a render,. observers to be defined at the
* chart level
*****************************************************************/
_renderSeriesOnTop: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
var targets = [],
ctx;
//search for the series we want to redraw
for(var j=0; j<this._canvasTargets['chartData'].length; j++) {
if(this._canvasTargets['chartData'][j].target.seriesId === this.serieToRedrawOnTop) {
targets.push(this._canvasTargets['chartData'][j]);
}
}
for(var j=0; j<this._canvasTargets['filteredChartData'].length; j++) {
if(this._canvasTargets['filteredChartData'][j].target.seriesId === this.serieToRedrawOnTop) {
targets.push(this._canvasTargets['filteredChartData'][j]);
}
}
if(targets.length) {
var ctx = {
'lastPointRenderedIndex': null,
'currentBatchStartIndex': 0,
'renderType': 'chartData',
'canvasTargets': targets,
'svgTargets': this._svgTargets['chartData'],
'canvasToClear': [],
'drawDebounceTime': 0
}
this._renderData(ctx);
}
},
_renderTypedContext: function(renderType, canvasesToClear) {
// we want the _canvasTargets to not be a link that can change mid debounce
var copy = [];
for(var i = 0; i < this._canvasTargets[renderType].length; i++) {
copy.push(this._canvasTargets[renderType][i]);
}
//sort based on priority
copy.sort(function(a,b) {
return Px.d3.ascending(a.priority, b.priority);
});
var ctx = {
'lastPointRenderedIndex': null,
'currentBatchStartIndex': 0,
'renderType': renderType,
'canvasTargets': copy,
'svgTargets': this._svgTargets[renderType],
'canvasToClear': canvasesToClear,
'drawDebounceTime': this.drawDebounceTime[renderType]
};
if(ctx.canvasTargets.length) {
this._renderData(ctx);
} else {
//make sure the canvas is cleared
for(var i=0; i<ctx.canvasToClear.length; i++) {
if(ctx.canvasToClear[i] && ctx.canvasToClear[i].pxClearCanvas) {
ctx.canvasToClear[i].pxClearCanvas();
}
}
}
},
_renderChartData: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(this.chartData && this.chartData.length) {
this._renderTypedContext('chartData', [this.canvasContext]);
} else {
//make sure the canvas is clear
this.canvasContext.pxClearCanvas();
}
},
_renderFilteredChartData: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(this._filteredData && this._filteredData.length) {
this._renderTypedContext('filteredChartData', [this.canvasContext]);
} else {
//make sure the canvas is clear
this.canvasContext.pxClearCanvas();
}
},
_renderHighlight: function() {
if(this.hasUndefinedArguments(arguments) ||
!this.domainChanged ||
!this.canvasLayers.highlighter ||
!this.completeSeriesConfig ||
this.preventInitialDrawing) {
return;
}
this._renderTypedContext('highlightData', [this.canvasLayers.highlighter]);
},
_renderMarkers: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
this._renderTypedContext('markers', [this.canvasLayers.markers]);
},
_renderAllLines: function() {
var canvasTargets = [],
clears = this.canvasLayers.highlighter ? [this.canvasContext, this.canvasLayers.highlighter] : [this.canvasContext],
keys = Object.keys(this._canvasTargets),
ctx;
//search all lines in highlight and data
for(var i=0; i<keys.length;i++) {
var cur = this._canvasTargets[keys[i]];
for(var j=0; j<cur.length; j++) {
if(cur[j].type === 'line') {
canvasTargets.push(cur[j]);
}
}
}
ctx = {
'lastPointRenderedIndex': null,
'currentBatchStartIndex': 0,
'renderType': 'chartData',
'canvasTargets': canvasTargets,
'svgTargets': this._svgTargets['chartData'],
'canvasToClear': clears,
'drawDebounceTime': this.drawDebounceTime['chartData']
}
this._renderData(ctx);
},
/*****************************************************************
* Rendering process
*****************************************************************/
/**
* Initial entry point, debouncing as needed or cancel
*/
_renderData: function(ctx) {
if(!this.preventInitialDrawing) {
//new request
this._progressiveRenderingCounter[ctx.renderType]++;
if(ctx.drawDebounceTime > 0) {
this.debounce(ctx.renderType, function() {
this._renderDataDebounced(ctx, true);
}.bind(this), ctx.drawDebounceTime);
} else {
this._renderDataDebounced(ctx, true);
}
} else {
//reset counter so it cancels current drawing
this._progressiveRenderingCounter[ctx.renderType] = 0;
}
},
/**
* Ensure we the basic conditions for allowign rendering
* and start it
*/
_renderDataDebounced: function(ctx, allowCanvasClearing) {
if(this.y &&
this.domainChanged &&
this._isAttached) {
this.fire('px-vis-chart-canvas-rendering-started', {'context': ctx});
this._initializeCanvasRendering(ctx, allowCanvasClearing);
}
},
/**
* Resets var relating to 1 complete rendering, call initializeDrawingSession
* on all rendering targets and kick the process
*/
_initializeCanvasRendering: function(ctx, allowCanvasClearing) {
//clear canvas first
for(var i=0; i<ctx.canvasToClear.length; i++) {
ctx.canvasToClear[i].pxClearCanvas();
}
ctx.frameIndex= 0;
//new request
ctx.requestCounter = ++this._progressiveRenderingCounter[ctx.renderType],
ctx.targetIndex = 0,
ctx.currentRenderingCounter = 0
//initialize all elements that need to draw
if(ctx.canvasTargets.length) {
for(var i=0; i<ctx.canvasTargets.length; i++) {
ctx.canvasTargets[i].target.initializeDrawingSession();
}
//now start actual drawing
this._processCanvasRendering(ctx);
}
},
/**
* Called each frame.
* - Updates previous frame timings if there was one
* - Render what can be in the current frame
* - Exit or wait for next frame
*/
_processCanvasRendering: function(ctx) {
var now = window.performance.now(),
previousTargetsFrames,
pointsRendered = 0,
allRenderedTargetSameType = true;
Px.vis.debug.info(' ' , 'renderer');
Px.vis.debug.info('STARTING ONE FRAME', 'renderer');
this._updatePreviousFrameTiming(ctx, now);
if(ctx.requestCounter !== this._progressiveRenderingCounter[ctx.renderType]) {
//new request came in, cancel this drawing. Don't reset the counter as we
//want the new request to finish
return;
}
ctx.currentTarget = this._getCurrentCanvasRenderingTarget(ctx);
ctx.previousStartTime = now;
this._processCanvasOneFrame(ctx);
ctx.frameIndex++;
if(ctx.targetIndex > ctx.canvasTargets.length-1) {
//make sure we restore target frame timing if we had to change it
this._internalRendererFrameDurationTarget = this.rendererFrameDurationTarget;
//Everything done
this.fire('px-vis-chart-canvas-rendering-ended', {'context': ctx});
} else {
//keep rendering
//wrap function so that we can still pass the context
window.requestAnimationFrame(function() { this._processCanvasRendering(ctx); }.bind(this));
}
},
/**
* Rendering process during one frame. Calculate how many points can be
* rendered for the current target an render those. Keep rendering next
* targets if we have enough time, based on same process
*/
_processCanvasOneFrame: function(ctx) {
//budget is how much we can do in our frame. keep rendering until we run
//out of budget or rendering target
var budget = 100,
previousRenderTargetType = null,
toRender,
totalRendered = 0,
drawingResult;
while(budget > 0 && ctx.currentTarget) {
//get how many points we can render
if(previousRenderTargetType !== ctx.currentTarget.type) {
//different type of rendering, get allowance pro rated with what's left of our budget
toRender = this._calculatePointsAllowance(ctx);
previousRenderTargetType = ctx.currentTarget.type;
}
Px.vis.debug.info('NEW TARGET, torender: ' + toRender + ', budget left: ' + budget, 'renderer');
//wether we need to guess or have stats for this type of rendering
if(toRender === -1) {
drawingResult = this._firstCanvasRender(ctx);
//update toRender so that if we have a next target it can use those
//stats. toRender should be the number of points of the whole frame
//including what has just been rendered because it will be automatically
//adjusted by budget in the _renderTargetToCanvas
toRender = drawingResult.points * 100 / drawingResult.budgetUsed;
} else {
drawingResult = this._renderTargetToCanvas(toRender, ctx, budget);
}
//update how many points have been rendered for this target type during this frame
ctx.previousFrameStats.pointsCount[ctx.currentTarget.type] = ctx.previousFrameStats.pointsCount[ctx.currentTarget.type] ? ctx.previousFrameStats.pointsCount[ctx.currentTarget.type] + drawingResult.points : drawingResult.points;
ctx.previousFrameStats.totPoints += drawingResult.points;
budget -= drawingResult.budgetUsed;
//get next target and keep rendering if we can
ctx.currentTarget = this._getCurrentCanvasRenderingTarget(ctx);
}
Px.vis.debug.info('finished one frame: ' + JSON.stringify(ctx.previousFrameStats) + ' in: ' + (window.performance.now() - ctx.previousStartTime), 'renderer');
},
/**
* Updates stats of the previous frame: how many points have been
* rendered per type and how long it took
*/
_updatePreviousFrameTiming: function(ctx, now) {
if(ctx.previousFrameStats) {
//update how long the previous frame took. Ugly syntax, sorry
var keys = Object.keys(ctx.previousFrameStats.pointsCount),
targetType;
//find each type of render that happened last frame
for(var i=0; i< keys.length; i++) {
targetType = keys[i];
if(ctx.previousFrameStats.pointsCount[targetType]) {
//if we rendered different types prorata the duration
this._previousFramesTiming[ctx.renderType][targetType].push({
'points': ctx.previousFrameStats.pointsCount[targetType],
'duration': (now - ctx.previousStartTime)*(ctx.previousFrameStats.pointsCount[targetType]/ctx.previousFrameStats.totPoints)
});
//only keep a certain number of frame timing to average
if(this._previousFramesTiming[ctx.renderType][targetType].length > this.rendererFrameCountToAverage) {
this._previousFramesTiming[ctx.renderType][targetType].shift();
}
Px.vis.debug.info('frame ' + ctx.frameIndex + ', type: ' + targetType + ', render: ' +JSON.stringify(this._previousFramesTiming[ctx.renderType][targetType][this._previousFramesTiming[ctx.renderType][targetType].length-1]), 'renderer');
}
}
}
//reset stat object
ctx.previousFrameStats = {};
ctx.previousFrameStats.pointsCount = {};
ctx.previousFrameStats.totPoints = 0;
},
_getCurrentCanvasRenderingTarget: function(ctx) {
if(ctx.canvasTargets.length) {
return ctx.canvasTargets[ctx.targetIndex];
}
return null;
},
/**
* Used when rendering a target we don't have stats about. Assumes a first
* number of points to render, measure that and render more if we think we can
*/
_firstCanvasRender: function(ctx) {
//try estimating how much we can render.
var duration,
multiplier,
targetTiming = this._internalRendererFrameDurationTarget-4,
pointsRendered = 0,
result,
before = window.performance.now(),
toRender = Math.min(ctx.currentTarget.type === 'scatter' ? 200 : 1000, ctx.currentTarget.target.chartData ? ctx.currentTarget.target.chartData.length : 0),
budgetUsed;
if(toRender) {
//start by rendering X pts
this._renderTargetToCanvas(toRender, ctx, 100)
pointsRendered = toRender;
duration = window.performance.now() - before;
//target our duration frame - 4ms: - 4ms for the browser to
//actually draw. Crude but this is only for the first frame
if(duration < targetTiming) {
//find how much more we can render
multiplier = Math.floor(targetTiming / duration);
//render more, but we might hit the end of this series
result = this._renderTargetToCanvas(multiplier * toRender, ctx, 100);
pointsRendered += result.points;
duration = window.performance.now() - before;
}
//if we have rendered less points than the estimation don't use all the budget
// budgetUsed = (pointsRendered*100)/(toRender + multiplier*10);
//adjust budget in case we finished rendering that series
// budgetUsed = pointsRendered/(toRender * (multiplier+1));
budgetUsed = duration/targetTiming * 100;
return { 'points': pointsRendered, 'budgetUsed': budgetUsed};
} else {
//nothing to render, keep going
ctx.currentRenderingCounter = 0;
ctx.targetIndex++;
return { 'points': 0, 'budgetUsed': 0};
}
},
/**
* Tries to render toRender number of points for the current target.
* returns the number of points actually rendered and how much of the budget
* this used
*/
_renderTargetToCanvas: function(toRender, ctx, currentBudget) {
var leftInCurrentSeries = ctx.currentTarget.target.chartData ? ctx.currentTarget.target.chartData.length - ctx.currentRenderingCounter : 0,
start,
stop,
proRatedToRender = Math.floor(toRender * currentBudget /100);
Px.vis.debug.info('trying to render target with ' + proRatedToRender + ' points for target of ' + toRender + ' with budget of ' + currentBudget, 'renderer');
if(leftInCurrentSeries > 0) {
start = ctx.currentRenderingCounter;
stop = Math.min(start + proRatedToRender, ctx.currentTarget.target.chartData.length);
ctx.currentTarget.target.renderOneBatch(start, stop);
} else {
start = 0;
stop = 0;
}
if(proRatedToRender > leftInCurrentSeries) {
//this series is done
ctx.currentRenderingCounter = 0;
ctx.targetIndex++;
Px.vis.debug.info('rendered target ' + (stop-start) + ' points, used budget of ' + Math.floor((stop-start) * 100 / toRender), 'renderer');
//return how many points we rendered
return { 'points': stop-start, 'budgetUsed': Math.floor((stop-start) * 100 / toRender)};
} else {
Px.vis.debug.info('rendered target ' + (stop-start) + ' points, used budget of ' + currentBudget, 'renderer');
ctx.currentRenderingCounter += proRatedToRender;
return { 'points': stop-start, 'budgetUsed': currentBudget};
}
},
/**
* Calculates how many points we can render in one frame for the
* context current target. Based on stats of previous rendering of same type.
* Returns -1 if we don't have stats about this type of rendering
*/
_calculatePointsAllowance: function(ctx) {
var totPoints = 0,
totDuration = 0,
avgPoints,
avgDuration,
pointsAddition,
ptsPerMs,
framesArray = this._previousFramesTiming[ctx.renderType][ctx.currentTarget.type],
result;
if(framesArray.length > 0) {
//calculate averages
for(var i=0; i<framesArray.length; i++) {
totPoints += framesArray[i].points;
totDuration += framesArray[i].duration;
}
//adjust batch size
avgPoints = Math.floor(totPoints/framesArray.length);
avgDuration = totDuration/framesArray.length;
ptsPerMs = totPoints/totDuration;
//aim for more than 16ms. This is crucial since when not busy requestanimationframe will give us a callback
//every ~16 ms, so we HAVE to aim a bit higher to be sure we are keeping the browser busy
result = Math.floor(ptsPerMs*this._internalRendererFrameDurationTarget);
//if our average is too close to the minimum points rendered then
//aim at 30 fps instead of 60. This mainly aims at mitigating
//screens with refresh rate between 30 and 60 Hz, without minimal
//impact to the usual mechanism
if(this._internalRendererFrameDurationTarget < 37 && result < 1.05*this.rendererMinimumPointsPerFrame) {
this._internalRendererFrameDurationTarget = 37;
}
Px.vis.debug.info('calculating points allowance, stats: ' + JSON.stringify(framesArray) +' points: ' + Math.max(this.rendererMinimumPointsPerFrame, Math.floor(ptsPerMs*this._internalRendererFrameDurationTarget), 'renderer'));
return Math.max(this.rendererMinimumPointsPerFrame, Math.floor(ptsPerMs*this._internalRendererFrameDurationTarget));
} else {
//no stats
return -1;
}
},
_targetTimingChanged: function() {
this.set('_internalRendererFrameDurationTarget', this.rendererFrameDurationTarget);
}
},
PxVisBehaviorD3.renderToCanvas,
PxVisBehavior.dataset,
PxVisBehavior.preventInitialDrawing,
PxVisBehavior.isAttached,
PxVisBehaviorRenderer.debounceOnPanning,
PxVisBehaviorD3.domainUpdate,
PxVisBehavior.mutedSeries,
PxVisBehavior.completeSeriesConfig
];
</script>