WGLRenderer.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. /* *
  2. *
  3. * Copyright (c) 2019-2021 Highsoft AS
  4. *
  5. * Boost module: stripped-down renderer for higher performance
  6. *
  7. * License: highcharts.com/license
  8. *
  9. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  10. *
  11. * */
  12. 'use strict';
  13. import Color from '../../Core/Color/Color.js';
  14. var color = Color.parse;
  15. import GLShader from './WGLShader.js';
  16. import GLVertexBuffer from './WGLVBuffer.js';
  17. import H from '../../Core/Globals.js';
  18. var doc = H.doc;
  19. import U from '../../Core/Utilities.js';
  20. var isNumber = U.isNumber, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick;
  21. /* eslint-disable valid-jsdoc */
  22. /**
  23. * Main renderer. Used to render series.
  24. *
  25. * Notes to self:
  26. * - May be able to build a point map by rendering to a separate canvas and
  27. * encoding values in the color data.
  28. * - Need to figure out a way to transform the data quicker
  29. *
  30. * @private
  31. * @function GLRenderer
  32. *
  33. * @param {Function} postRenderCallback
  34. *
  35. * @return {*}
  36. */
  37. function GLRenderer(postRenderCallback) {
  38. // // Shader
  39. var shader = false,
  40. // Vertex buffers - keyed on shader attribute name
  41. vbuffer = false, vlen = 0,
  42. // Opengl context
  43. gl = false,
  44. // Width of our viewport in pixels
  45. width = 0,
  46. // Height of our viewport in pixels
  47. height = 0,
  48. // The data to render - array of coordinates
  49. data = false,
  50. // The marker data
  51. markerData = false,
  52. // Exports
  53. exports = {},
  54. // Is it inited?
  55. isInited = false,
  56. // The series stack
  57. series = [],
  58. // Texture handles
  59. textureHandles = {},
  60. // Things to draw as "rectangles" (i.e lines)
  61. asBar = {
  62. 'column': true,
  63. 'columnrange': true,
  64. 'bar': true,
  65. 'area': true,
  66. 'arearange': true
  67. }, asCircle = {
  68. 'scatter': true,
  69. 'bubble': true
  70. },
  71. // Render settings
  72. settings = {
  73. pointSize: 1,
  74. lineWidth: 1,
  75. fillColor: '#AA00AA',
  76. useAlpha: true,
  77. usePreallocated: false,
  78. useGPUTranslations: false,
  79. debug: {
  80. timeRendering: false,
  81. timeSeriesProcessing: false,
  82. timeSetup: false,
  83. timeBufferCopy: false,
  84. timeKDTree: false,
  85. showSkipSummary: false
  86. }
  87. };
  88. // /////////////////////////////////////////////////////////////////////////
  89. /**
  90. * @private
  91. */
  92. function setOptions(options) {
  93. merge(true, settings, options);
  94. }
  95. /**
  96. * @private
  97. */
  98. function seriesPointCount(series) {
  99. var isStacked, xData, s;
  100. if (series.isSeriesBoosting) {
  101. isStacked = !!series.options.stacking;
  102. xData = (series.xData ||
  103. series.options.xData ||
  104. series.processedXData);
  105. s = (isStacked ? series.data : (xData || series.options.data))
  106. .length;
  107. if (series.type === 'treemap') {
  108. s *= 12;
  109. }
  110. else if (series.type === 'heatmap') {
  111. s *= 6;
  112. }
  113. else if (asBar[series.type]) {
  114. s *= 2;
  115. }
  116. return s;
  117. }
  118. return 0;
  119. }
  120. /**
  121. * Allocate a float buffer to fit all series
  122. * @private
  123. */
  124. function allocateBuffer(chart) {
  125. var s = 0;
  126. if (!settings.usePreallocated) {
  127. return;
  128. }
  129. chart.series.forEach(function (series) {
  130. if (series.isSeriesBoosting) {
  131. s += seriesPointCount(series);
  132. }
  133. });
  134. vbuffer.allocate(s);
  135. }
  136. /**
  137. * @private
  138. */
  139. function allocateBufferForSingleSeries(series) {
  140. var s = 0;
  141. if (!settings.usePreallocated) {
  142. return;
  143. }
  144. if (series.isSeriesBoosting) {
  145. s = seriesPointCount(series);
  146. }
  147. vbuffer.allocate(s);
  148. }
  149. /**
  150. * Returns an orthographic perspective matrix
  151. * @private
  152. * @param {number} width - the width of the viewport in pixels
  153. * @param {number} height - the height of the viewport in pixels
  154. */
  155. function orthoMatrix(width, height) {
  156. var near = 0, far = 1;
  157. return [
  158. 2 / width, 0, 0, 0,
  159. 0, -(2 / height), 0, 0,
  160. 0, 0, -2 / (far - near), 0,
  161. -1, 1, -(far + near) / (far - near), 1
  162. ];
  163. }
  164. /**
  165. * Clear the depth and color buffer
  166. * @private
  167. */
  168. function clear() {
  169. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  170. }
  171. /**
  172. * Get the WebGL context
  173. * @private
  174. * @returns {WebGLContext} - the context
  175. */
  176. function getGL() {
  177. return gl;
  178. }
  179. /**
  180. * Push data for a single series
  181. * This calculates additional vertices and transforms the data to be
  182. * aligned correctly in memory
  183. * @private
  184. */
  185. function pushSeriesData(series, inst) {
  186. var isRange = (series.pointArrayMap &&
  187. series.pointArrayMap.join(',') === 'low,high'), chart = series.chart, options = series.options, isStacked = !!options.stacking, rawData = options.data, xExtremes = series.xAxis.getExtremes(), xMin = xExtremes.min, xMax = xExtremes.max, yExtremes = series.yAxis.getExtremes(), yMin = yExtremes.min, yMax = yExtremes.max, xData = series.xData || options.xData || series.processedXData, yData = series.yData || options.yData || series.processedYData, zData = (series.zData || options.zData ||
  188. series.processedZData), yAxis = series.yAxis, xAxis = series.xAxis,
  189. // plotHeight = series.chart.plotHeight,
  190. plotWidth = series.chart.plotWidth, useRaw = !xData || xData.length === 0,
  191. // threshold = options.threshold,
  192. // yBottom = chart.yAxis[0].getThreshold(threshold),
  193. // hasThreshold = isNumber(threshold),
  194. // colorByPoint = series.options.colorByPoint,
  195. // This is required for color by point, so make sure this is
  196. // uncommented if enabling that
  197. // colorIndex = 0,
  198. // Required for color axis support
  199. // caxis,
  200. connectNulls = options.connectNulls,
  201. // For some reason eslint/TypeScript don't pick up that this is
  202. // actually used: --- bre1470: it is never read, just set
  203. // maxVal: (number|undefined), // eslint-disable-line no-unused-vars
  204. points = series.points || false, lastX = false, lastY = false, minVal, scolor, sdata = isStacked ? series.data : (xData || rawData), closestLeft = { x: Number.MAX_VALUE, y: 0 }, closestRight = { x: -Number.MAX_VALUE, y: 0 },
  205. //
  206. skipped = 0, hadPoints = false,
  207. //
  208. cullXThreshold = 1, cullYThreshold = 1,
  209. // The following are used in the builder while loop
  210. x, y, d, z, i = -1, px = false, nx = false, low, chartDestroyed = typeof chart.index === 'undefined', nextInside = false, prevInside = false, pcolor = false, drawAsBar = asBar[series.type], isXInside = false, isYInside = true, firstPoint = true, zoneAxis = options.zoneAxis || 'y', zones = options.zones || false, zoneDefColor = false, threshold = options.threshold, gapSize = false;
  211. if (options.boostData && options.boostData.length > 0) {
  212. return;
  213. }
  214. if (options.gapSize) {
  215. gapSize = options.gapUnit !== 'value' ?
  216. options.gapSize * series.closestPointRange :
  217. options.gapSize;
  218. }
  219. if (zones) {
  220. zones.some(function (zone) {
  221. if (typeof zone.value === 'undefined') {
  222. zoneDefColor = new Color(zone.color);
  223. return true;
  224. }
  225. return false;
  226. });
  227. if (!zoneDefColor) {
  228. zoneDefColor = ((series.pointAttribs && series.pointAttribs().fill) ||
  229. series.color);
  230. zoneDefColor = new Color(zoneDefColor);
  231. }
  232. }
  233. if (chart.inverted) {
  234. // plotHeight = series.chart.plotWidth;
  235. plotWidth = series.chart.plotHeight;
  236. }
  237. series.closestPointRangePx = Number.MAX_VALUE;
  238. /**
  239. * Push color to color buffer - need to do this per vertex.
  240. * @private
  241. */
  242. function pushColor(color) {
  243. if (color) {
  244. inst.colorData.push(color[0]);
  245. inst.colorData.push(color[1]);
  246. inst.colorData.push(color[2]);
  247. inst.colorData.push(color[3]);
  248. }
  249. }
  250. /**
  251. * Push a vertice to the data buffer.
  252. * @private
  253. */
  254. function vertice(x, y, checkTreshold, pointSize, color) {
  255. pushColor(color);
  256. if (settings.usePreallocated) {
  257. vbuffer.push(x, y, checkTreshold ? 1 : 0, pointSize || 1);
  258. vlen += 4;
  259. }
  260. else {
  261. data.push(x);
  262. data.push(y);
  263. data.push(checkTreshold ? 1 : 0);
  264. data.push(pointSize || 1);
  265. }
  266. }
  267. /**
  268. * @private
  269. */
  270. function closeSegment() {
  271. if (inst.segments.length) {
  272. inst.segments[inst.segments.length - 1].to = data.length || vlen;
  273. }
  274. }
  275. /**
  276. * Create a new segment for the current set.
  277. * @private
  278. */
  279. function beginSegment() {
  280. // Insert a segment on the series.
  281. // A segment is just a start indice.
  282. // When adding a segment, if one exists from before, it should
  283. // set the previous segment's end
  284. if (inst.segments.length &&
  285. inst.segments[inst.segments.length - 1].from === (data.length || vlen)) {
  286. return;
  287. }
  288. closeSegment();
  289. inst.segments.push({
  290. from: data.length || vlen
  291. });
  292. }
  293. /**
  294. * Push a rectangle to the data buffer.
  295. * @private
  296. */
  297. function pushRect(x, y, w, h, color) {
  298. pushColor(color);
  299. vertice(x + w, y);
  300. pushColor(color);
  301. vertice(x, y);
  302. pushColor(color);
  303. vertice(x, y + h);
  304. pushColor(color);
  305. vertice(x, y + h);
  306. pushColor(color);
  307. vertice(x + w, y + h);
  308. pushColor(color);
  309. vertice(x + w, y);
  310. }
  311. // Create the first segment
  312. beginSegment();
  313. // Special case for point shapes
  314. if (points && points.length > 0) {
  315. // If we're doing points, we assume that the points are already
  316. // translated, so we skip the shader translation.
  317. inst.skipTranslation = true;
  318. // Force triangle draw mode
  319. inst.drawMode = 'triangles';
  320. // We don't have a z component in the shader, so we need to sort.
  321. if (points[0].node && points[0].node.levelDynamic) {
  322. points.sort(function (a, b) {
  323. if (a.node) {
  324. if (a.node.levelDynamic >
  325. b.node.levelDynamic) {
  326. return 1;
  327. }
  328. if (a.node.levelDynamic <
  329. b.node.levelDynamic) {
  330. return -1;
  331. }
  332. }
  333. return 0;
  334. });
  335. }
  336. points.forEach(function (point) {
  337. var plotY = point.plotY, swidth, pointAttr;
  338. if (typeof plotY !== 'undefined' &&
  339. !isNaN(plotY) &&
  340. point.y !== null &&
  341. point.shapeArgs) {
  342. var _a = point.shapeArgs, _b = _a.x, x_1 = _b === void 0 ? 0 : _b, _c = _a.y, y_1 = _c === void 0 ? 0 : _c, _d = _a.width, width_1 = _d === void 0 ? 0 : _d, _e = _a.height, height_1 = _e === void 0 ? 0 : _e;
  343. pointAttr = chart.styledMode ?
  344. point.series
  345. .colorAttribs(point) :
  346. pointAttr = point.series.pointAttribs(point);
  347. swidth = pointAttr['stroke-width'] || 0;
  348. // Handle point colors
  349. pcolor = color(pointAttr.fill).rgba;
  350. pcolor[0] /= 255.0;
  351. pcolor[1] /= 255.0;
  352. pcolor[2] /= 255.0;
  353. // So there are two ways of doing this. Either we can
  354. // create a rectangle of two triangles, or we can do a
  355. // point and use point size. Latter is faster, but
  356. // only supports squares. So we're doing triangles.
  357. // We could also use one color per. vertice to get
  358. // better color interpolation.
  359. // If there's stroking, we do an additional rect
  360. if (series.type === 'treemap') {
  361. swidth = swidth || 1;
  362. scolor = color(pointAttr.stroke).rgba;
  363. scolor[0] /= 255.0;
  364. scolor[1] /= 255.0;
  365. scolor[2] /= 255.0;
  366. pushRect(x_1, y_1, width_1, height_1, scolor);
  367. swidth /= 2;
  368. }
  369. // } else {
  370. // swidth = 0;
  371. // }
  372. // Fixes issues with inverted heatmaps (see #6981)
  373. // The root cause is that the coordinate system is flipped.
  374. // In other words, instead of [0,0] being top-left, it's
  375. // bottom-right. This causes a vertical and horizontal flip
  376. // in the resulting image, making it rotated 180 degrees.
  377. if (series.type === 'heatmap' && chart.inverted) {
  378. x_1 = xAxis.len - x_1;
  379. y_1 = yAxis.len - y_1;
  380. width_1 = -width_1;
  381. height_1 = -height_1;
  382. }
  383. pushRect(x_1 + swidth, y_1 + swidth, width_1 - (swidth * 2), height_1 - (swidth * 2), pcolor);
  384. }
  385. });
  386. closeSegment();
  387. return;
  388. }
  389. // Extract color axis
  390. // (chart.axes || []).forEach(function (a) {
  391. // if (H.ColorAxis && a instanceof H.ColorAxis) {
  392. // caxis = a;
  393. // }
  394. // });
  395. while (i < sdata.length - 1) {
  396. d = sdata[++i];
  397. if (typeof d === 'undefined') {
  398. continue;
  399. }
  400. // px = x = y = z = nx = low = false;
  401. // chartDestroyed = typeof chart.index === 'undefined';
  402. // nextInside = prevInside = pcolor = isXInside = isYInside = false;
  403. // drawAsBar = asBar[series.type];
  404. if (chartDestroyed) {
  405. break;
  406. }
  407. // Uncomment this to enable color by point.
  408. // This currently left disabled as the charts look really ugly
  409. // when enabled and there's a lot of points.
  410. // Leaving in for the future (tm).
  411. // if (colorByPoint) {
  412. // colorIndex = ++colorIndex %
  413. // series.chart.options.colors.length;
  414. // pcolor = toRGBAFast(series.chart.options.colors[colorIndex]);
  415. // pcolor[0] /= 255.0;
  416. // pcolor[1] /= 255.0;
  417. // pcolor[2] /= 255.0;
  418. // }
  419. // Handle the point.color option (#5999)
  420. var pointOptions = rawData && rawData[i];
  421. if (!useRaw && isObject(pointOptions, true)) {
  422. if (pointOptions.color) {
  423. pcolor = color(pointOptions.color).rgba;
  424. pcolor[0] /= 255.0;
  425. pcolor[1] /= 255.0;
  426. pcolor[2] /= 255.0;
  427. }
  428. }
  429. if (useRaw) {
  430. x = d[0];
  431. y = d[1];
  432. if (sdata[i + 1]) {
  433. nx = sdata[i + 1][0];
  434. }
  435. if (sdata[i - 1]) {
  436. px = sdata[i - 1][0];
  437. }
  438. if (d.length >= 3) {
  439. z = d[2];
  440. if (d[2] > inst.zMax) {
  441. inst.zMax = d[2];
  442. }
  443. if (d[2] < inst.zMin) {
  444. inst.zMin = d[2];
  445. }
  446. }
  447. }
  448. else {
  449. x = d;
  450. y = yData[i];
  451. if (sdata[i + 1]) {
  452. nx = sdata[i + 1];
  453. }
  454. if (sdata[i - 1]) {
  455. px = sdata[i - 1];
  456. }
  457. if (zData && zData.length) {
  458. z = zData[i];
  459. if (zData[i] > inst.zMax) {
  460. inst.zMax = zData[i];
  461. }
  462. if (zData[i] < inst.zMin) {
  463. inst.zMin = zData[i];
  464. }
  465. }
  466. }
  467. if (!connectNulls && (x === null || y === null)) {
  468. beginSegment();
  469. continue;
  470. }
  471. if (nx && nx >= xMin && nx <= xMax) {
  472. nextInside = true;
  473. }
  474. if (px && px >= xMin && px <= xMax) {
  475. prevInside = true;
  476. }
  477. if (isRange) {
  478. if (useRaw) {
  479. y = d.slice(1, 3);
  480. }
  481. low = y[0];
  482. y = y[1];
  483. }
  484. else if (isStacked) {
  485. x = d.x;
  486. y = d.stackY;
  487. low = y - d.y;
  488. }
  489. if (yMin !== null &&
  490. typeof yMin !== 'undefined' &&
  491. yMax !== null &&
  492. typeof yMax !== 'undefined') {
  493. isYInside = y >= yMin && y <= yMax;
  494. }
  495. if (x > xMax && closestRight.x < xMax) {
  496. closestRight.x = x;
  497. closestRight.y = y;
  498. }
  499. if (x < xMin && closestLeft.x > xMin) {
  500. closestLeft.x = x;
  501. closestLeft.y = y;
  502. }
  503. if (y === null && connectNulls) {
  504. continue;
  505. }
  506. // Cull points outside the extremes
  507. if (y === null || (!isYInside && !nextInside && !prevInside)) {
  508. beginSegment();
  509. continue;
  510. }
  511. // The first point before and first after extremes should be
  512. // rendered (#9962)
  513. if ((nx >= xMin || x >= xMin) &&
  514. (px <= xMax || x <= xMax)) {
  515. isXInside = true;
  516. }
  517. if (!isXInside && !nextInside && !prevInside) {
  518. continue;
  519. }
  520. if (gapSize && x - px > gapSize) {
  521. beginSegment();
  522. }
  523. // Note: Boost requires that zones are sorted!
  524. if (zones) {
  525. pcolor = zoneDefColor.rgba.slice();
  526. zones.some(function (// eslint-disable-line no-loop-func
  527. zone, i) {
  528. var last = zones[i - 1];
  529. if (zoneAxis === 'x') {
  530. if (typeof zone.value !== 'undefined' && x <= zone.value) {
  531. if (!last || x >= last.value) {
  532. pcolor = color(zone.color).rgba;
  533. }
  534. return true;
  535. }
  536. return false;
  537. }
  538. if (typeof zone.value !== 'undefined' && y <= zone.value) {
  539. if (!last || y >= last.value) {
  540. pcolor = color(zone.color).rgba;
  541. }
  542. return true;
  543. }
  544. return false;
  545. });
  546. pcolor[0] /= 255.0;
  547. pcolor[1] /= 255.0;
  548. pcolor[2] /= 255.0;
  549. }
  550. // Skip translations - temporary floating point fix
  551. if (!settings.useGPUTranslations) {
  552. inst.skipTranslation = true;
  553. x = xAxis.toPixels(x, true);
  554. y = yAxis.toPixels(y, true);
  555. // Make sure we're not drawing outside of the chart area.
  556. // See #6594. Update: this is no longer required as far as I
  557. // can tell. Leaving in for git blame in case there are edge
  558. // cases I've not found. Having this in breaks #10246.
  559. // if (y > plotHeight) {
  560. // y = plotHeight;
  561. // }
  562. if (x > plotWidth) {
  563. // If this is rendered as a point, just skip drawing it
  564. // entirely, as we're not dependandt on lineTo'ing to it.
  565. // See #8197
  566. if (inst.drawMode === 'points') {
  567. continue;
  568. }
  569. // Having this here will clamp markers and make the angle
  570. // of the last line wrong. See 9166.
  571. // x = plotWidth;
  572. }
  573. }
  574. // No markers on out of bounds things.
  575. // Out of bound things are shown if and only if the next
  576. // or previous point is inside the rect.
  577. if (inst.hasMarkers && isXInside) {
  578. // x = Highcharts.correctFloat(
  579. // Math.min(Math.max(-1e5, xAxis.translate(
  580. // x,
  581. // 0,
  582. // 0,
  583. // 0,
  584. // 1,
  585. // 0.5,
  586. // false
  587. // )), 1e5)
  588. // );
  589. if (lastX !== false) {
  590. series.closestPointRangePx = Math.min(series.closestPointRangePx, Math.abs(x - lastX));
  591. }
  592. }
  593. // If the last _drawn_ point is closer to this point than the
  594. // threshold, skip it. Shaves off 20-100ms in processing.
  595. if (!settings.useGPUTranslations &&
  596. !settings.usePreallocated &&
  597. (lastX && Math.abs(x - lastX) < cullXThreshold) &&
  598. (lastY && Math.abs(y - lastY) < cullYThreshold)) {
  599. if (settings.debug.showSkipSummary) {
  600. ++skipped;
  601. }
  602. continue;
  603. }
  604. if (drawAsBar) {
  605. // maxVal = y;
  606. minVal = low;
  607. if (low === false || typeof low === 'undefined') {
  608. if (y < 0) {
  609. minVal = y;
  610. }
  611. else {
  612. minVal = 0;
  613. }
  614. }
  615. if (!isRange && !isStacked) {
  616. minVal = Math.max(threshold === null ? yMin : threshold, // #5268
  617. yMin); // #8731
  618. }
  619. if (!settings.useGPUTranslations) {
  620. minVal = yAxis.toPixels(minVal, true);
  621. }
  622. // Need to add an extra point here
  623. vertice(x, minVal, 0, 0, pcolor);
  624. }
  625. // Do step line if enabled.
  626. // Draws an additional point at the old Y at the new X.
  627. // See #6976.
  628. if (options.step && !firstPoint) {
  629. vertice(x, lastY, 0, 2, pcolor);
  630. }
  631. vertice(x, y, 0, series.type === 'bubble' ? (z || 1) : 2, pcolor);
  632. // Uncomment this to support color axis.
  633. // if (caxis) {
  634. // pcolor = color(caxis.toColor(y)).rgba;
  635. // inst.colorData.push(color[0] / 255.0);
  636. // inst.colorData.push(color[1] / 255.0);
  637. // inst.colorData.push(color[2] / 255.0);
  638. // inst.colorData.push(color[3]);
  639. // }
  640. lastX = x;
  641. lastY = y;
  642. hadPoints = true;
  643. firstPoint = false;
  644. }
  645. if (settings.debug.showSkipSummary) {
  646. console.log('skipped points:', skipped); // eslint-disable-line no-console
  647. }
  648. /**
  649. * @private
  650. */
  651. function pushSupplementPoint(point, atStart) {
  652. if (!settings.useGPUTranslations) {
  653. inst.skipTranslation = true;
  654. point.x = xAxis.toPixels(point.x, true);
  655. point.y = yAxis.toPixels(point.y, true);
  656. }
  657. // We should only do this for lines, and we should ignore markers
  658. // since there's no point here that would have a marker.
  659. if (atStart) {
  660. data = [point.x, point.y, 0, 2].concat(data);
  661. return;
  662. }
  663. vertice(point.x, point.y, 0, 2);
  664. }
  665. if (!hadPoints &&
  666. connectNulls !== false &&
  667. series.drawMode === 'line_strip') {
  668. if (closestLeft.x < Number.MAX_VALUE) {
  669. // We actually need to push this *before* the complete buffer.
  670. pushSupplementPoint(closestLeft, true);
  671. }
  672. if (closestRight.x > -Number.MAX_VALUE) {
  673. pushSupplementPoint(closestRight);
  674. }
  675. }
  676. closeSegment();
  677. }
  678. /**
  679. * Push a series to the renderer
  680. * If we render the series immediatly, we don't have to loop later
  681. * @private
  682. * @param s {Highchart.Series} - the series to push
  683. */
  684. function pushSeries(s) {
  685. if (series.length > 0) {
  686. // series[series.length - 1].to = data.length;
  687. if (series[series.length - 1].hasMarkers) {
  688. series[series.length - 1].markerTo = markerData.length;
  689. }
  690. }
  691. if (settings.debug.timeSeriesProcessing) {
  692. console.time('building ' + s.type + ' series'); // eslint-disable-line no-console
  693. }
  694. var obj = {
  695. segments: [],
  696. // from: data.length,
  697. markerFrom: markerData.length,
  698. // Push RGBA values to this array to use per. point coloring.
  699. // It should be 0-padded, so each component should be pushed in
  700. // succession.
  701. colorData: [],
  702. series: s,
  703. zMin: Number.MAX_VALUE,
  704. zMax: -Number.MAX_VALUE,
  705. hasMarkers: s.options.marker ?
  706. s.options.marker.enabled !== false :
  707. false,
  708. showMarkers: true,
  709. drawMode: {
  710. 'area': 'lines',
  711. 'arearange': 'lines',
  712. 'areaspline': 'line_strip',
  713. 'column': 'lines',
  714. 'columnrange': 'lines',
  715. 'bar': 'lines',
  716. 'line': 'line_strip',
  717. 'scatter': 'points',
  718. 'heatmap': 'triangles',
  719. 'treemap': 'triangles',
  720. 'bubble': 'points'
  721. }[s.type] || 'line_strip'
  722. };
  723. if (s.index >= series.length) {
  724. series.push(obj);
  725. }
  726. else {
  727. series[s.index] = obj;
  728. }
  729. // Add the series data to our buffer(s)
  730. pushSeriesData(s, obj);
  731. if (settings.debug.timeSeriesProcessing) {
  732. console.timeEnd('building ' + s.type + ' series'); // eslint-disable-line no-console
  733. }
  734. }
  735. /**
  736. * Flush the renderer.
  737. * This removes pushed series and vertices.
  738. * Should be called after clearing and before rendering
  739. * @private
  740. */
  741. function flush() {
  742. series = [];
  743. exports.data = data = [];
  744. markerData = [];
  745. if (vbuffer) {
  746. vbuffer.destroy();
  747. }
  748. }
  749. /**
  750. * Pass x-axis to shader
  751. * @private
  752. * @param axis {Highcharts.Axis} - the x-axis
  753. */
  754. function setXAxis(axis) {
  755. if (!shader) {
  756. return;
  757. }
  758. shader.setUniform('xAxisTrans', axis.transA);
  759. shader.setUniform('xAxisMin', axis.min);
  760. shader.setUniform('xAxisMinPad', axis.minPixelPadding);
  761. shader.setUniform('xAxisPointRange', axis.pointRange);
  762. shader.setUniform('xAxisLen', axis.len);
  763. shader.setUniform('xAxisPos', axis.pos);
  764. shader.setUniform('xAxisCVSCoord', (!axis.horiz));
  765. shader.setUniform('xAxisIsLog', (!!axis.logarithmic));
  766. shader.setUniform('xAxisReversed', (!!axis.reversed));
  767. }
  768. /**
  769. * Pass y-axis to shader
  770. * @private
  771. * @param axis {Highcharts.Axis} - the y-axis
  772. */
  773. function setYAxis(axis) {
  774. if (!shader) {
  775. return;
  776. }
  777. shader.setUniform('yAxisTrans', axis.transA);
  778. shader.setUniform('yAxisMin', axis.min);
  779. shader.setUniform('yAxisMinPad', axis.minPixelPadding);
  780. shader.setUniform('yAxisPointRange', axis.pointRange);
  781. shader.setUniform('yAxisLen', axis.len);
  782. shader.setUniform('yAxisPos', axis.pos);
  783. shader.setUniform('yAxisCVSCoord', (!axis.horiz));
  784. shader.setUniform('yAxisIsLog', (!!axis.logarithmic));
  785. shader.setUniform('yAxisReversed', (!!axis.reversed));
  786. }
  787. /**
  788. * Set the translation threshold
  789. * @private
  790. * @param has {boolean} - has threshold flag
  791. * @param translation {Float} - the threshold
  792. */
  793. function setThreshold(has, translation) {
  794. shader.setUniform('hasThreshold', has);
  795. shader.setUniform('translatedThreshold', translation);
  796. }
  797. /**
  798. * Render the data
  799. * This renders all pushed series.
  800. * @private
  801. */
  802. function render(chart) {
  803. if (chart) {
  804. if (!chart.chartHeight || !chart.chartWidth) {
  805. // chart.setChartSize();
  806. }
  807. width = chart.chartWidth || 800;
  808. height = chart.chartHeight || 400;
  809. }
  810. else {
  811. return false;
  812. }
  813. if (!gl || !width || !height || !shader) {
  814. return false;
  815. }
  816. if (settings.debug.timeRendering) {
  817. console.time('gl rendering'); // eslint-disable-line no-console
  818. }
  819. gl.canvas.width = width;
  820. gl.canvas.height = height;
  821. shader.bind();
  822. gl.viewport(0, 0, width, height);
  823. shader.setPMatrix(orthoMatrix(width, height));
  824. if (settings.lineWidth > 1 && !H.isMS) {
  825. gl.lineWidth(settings.lineWidth);
  826. }
  827. vbuffer.build(exports.data, 'aVertexPosition', 4);
  828. vbuffer.bind();
  829. shader.setInverted(chart.inverted);
  830. // Render the series
  831. series.forEach(function (s, si) {
  832. var options = s.series.options, shapeOptions = options.marker, sindex, lineWidth = (typeof options.lineWidth !== 'undefined' ?
  833. options.lineWidth :
  834. 1), threshold = options.threshold, hasThreshold = isNumber(threshold), yBottom = s.series.yAxis.getThreshold(threshold), translatedThreshold = yBottom, cbuffer, showMarkers = pick(options.marker ? options.marker.enabled : null, s.series.xAxis.isRadial ? true : null, s.series.closestPointRangePx >
  835. 2 * ((options.marker ?
  836. options.marker.radius :
  837. 10) || 10)), fillColor, shapeTexture = textureHandles[(shapeOptions && shapeOptions.symbol) ||
  838. s.series.symbol] || textureHandles.circle, scolor = [];
  839. if (s.segments.length === 0 ||
  840. (s.segmentslength &&
  841. s.segments[0].from === s.segments[0].to)) {
  842. return;
  843. }
  844. if (shapeTexture.isReady) {
  845. gl.bindTexture(gl.TEXTURE_2D, shapeTexture.handle);
  846. shader.setTexture(shapeTexture.handle);
  847. }
  848. if (chart.styledMode) {
  849. fillColor = (s.series.markerGroup &&
  850. s.series.markerGroup.getStyle('fill'));
  851. }
  852. else {
  853. fillColor =
  854. (s.drawMode === 'points' && // #14260
  855. s.series.pointAttribs &&
  856. s.series.pointAttribs().fill) ||
  857. s.series.color;
  858. if (options.colorByPoint) {
  859. fillColor = s.series.chart.options.colors[si];
  860. }
  861. }
  862. if (s.series.fillOpacity && options.fillOpacity) {
  863. fillColor = new Color(fillColor).setOpacity(pick(options.fillOpacity, 1.0)).get();
  864. }
  865. scolor = color(fillColor).rgba;
  866. if (!settings.useAlpha) {
  867. scolor[3] = 1.0;
  868. }
  869. // This is very much temporary
  870. if (s.drawMode === 'lines' &&
  871. settings.useAlpha &&
  872. scolor[3] < 1) {
  873. scolor[3] /= 10;
  874. }
  875. // Blending
  876. if (options.boostBlending === 'add') {
  877. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  878. gl.blendEquation(gl.FUNC_ADD);
  879. }
  880. else if (options.boostBlending === 'mult' ||
  881. options.boostBlending === 'multiply') {
  882. gl.blendFunc(gl.DST_COLOR, gl.ZERO);
  883. }
  884. else if (options.boostBlending === 'darken') {
  885. gl.blendFunc(gl.ONE, gl.ONE);
  886. gl.blendEquation(gl.FUNC_MIN);
  887. }
  888. else {
  889. // gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  890. // gl.blendEquation(gl.FUNC_ADD);
  891. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  892. }
  893. shader.reset();
  894. // If there are entries in the colorData buffer, build and bind it.
  895. if (s.colorData.length > 0) {
  896. shader.setUniform('hasColor', 1.0);
  897. cbuffer = GLVertexBuffer(gl, shader); // eslint-disable-line new-cap
  898. cbuffer.build(s.colorData, 'aColor', 4);
  899. cbuffer.bind();
  900. }
  901. // Set series specific uniforms
  902. shader.setColor(scolor);
  903. setXAxis(s.series.xAxis);
  904. setYAxis(s.series.yAxis);
  905. setThreshold(hasThreshold, translatedThreshold);
  906. if (s.drawMode === 'points') {
  907. if (options.marker && isNumber(options.marker.radius)) {
  908. shader.setPointSize(options.marker.radius * 2.0);
  909. }
  910. else {
  911. shader.setPointSize(1);
  912. }
  913. }
  914. // If set to true, the toPixels translations in the shader
  915. // is skipped, i.e it's assumed that the value is a pixel coord.
  916. shader.setSkipTranslation(s.skipTranslation);
  917. if (s.series.type === 'bubble') {
  918. shader.setBubbleUniforms(s.series, s.zMin, s.zMax);
  919. }
  920. shader.setDrawAsCircle(asCircle[s.series.type] || false);
  921. // Do the actual rendering
  922. // If the line width is < 0, skip rendering of the lines. See #7833.
  923. if (lineWidth > 0 || s.drawMode !== 'line_strip') {
  924. for (sindex = 0; sindex < s.segments.length; sindex++) {
  925. // if (s.segments[sindex].from < s.segments[sindex].to) {
  926. vbuffer.render(s.segments[sindex].from, s.segments[sindex].to, s.drawMode);
  927. // }
  928. }
  929. }
  930. if (s.hasMarkers && showMarkers) {
  931. if (options.marker && isNumber(options.marker.radius)) {
  932. shader.setPointSize(options.marker.radius * 2.0);
  933. }
  934. else {
  935. shader.setPointSize(10);
  936. }
  937. shader.setDrawAsCircle(true);
  938. for (sindex = 0; sindex < s.segments.length; sindex++) {
  939. // if (s.segments[sindex].from < s.segments[sindex].to) {
  940. vbuffer.render(s.segments[sindex].from, s.segments[sindex].to, 'POINTS');
  941. // }
  942. }
  943. }
  944. });
  945. if (settings.debug.timeRendering) {
  946. console.timeEnd('gl rendering'); // eslint-disable-line no-console
  947. }
  948. if (postRenderCallback) {
  949. postRenderCallback();
  950. }
  951. flush();
  952. }
  953. /**
  954. * Render the data when ready
  955. * @private
  956. */
  957. function renderWhenReady(chart) {
  958. clear();
  959. if (chart.renderer.forExport) {
  960. return render(chart);
  961. }
  962. if (isInited) {
  963. render(chart);
  964. }
  965. else {
  966. setTimeout(function () {
  967. renderWhenReady(chart);
  968. }, 1);
  969. }
  970. }
  971. /**
  972. * Set the viewport size in pixels
  973. * Creates an orthographic perspective matrix and applies it.
  974. * @private
  975. * @param w {Integer} - the width of the viewport
  976. * @param h {Integer} - the height of the viewport
  977. */
  978. function setSize(w, h) {
  979. // Skip if there's no change, or if we have no valid shader
  980. if ((width === w && height === h) || !shader) {
  981. return;
  982. }
  983. width = w;
  984. height = h;
  985. shader.bind();
  986. shader.setPMatrix(orthoMatrix(width, height));
  987. }
  988. /**
  989. * Init OpenGL
  990. * @private
  991. * @param canvas {HTMLCanvas} - the canvas to render to
  992. */
  993. function init(canvas, noFlush) {
  994. var i = 0, contexts = [
  995. 'webgl',
  996. 'experimental-webgl',
  997. 'moz-webgl',
  998. 'webkit-3d'
  999. ];
  1000. isInited = false;
  1001. if (!canvas) {
  1002. return false;
  1003. }
  1004. if (settings.debug.timeSetup) {
  1005. console.time('gl setup'); // eslint-disable-line no-console
  1006. }
  1007. for (; i < contexts.length; i++) {
  1008. gl = canvas.getContext(contexts[i], {
  1009. // premultipliedAlpha: false
  1010. });
  1011. if (gl) {
  1012. break;
  1013. }
  1014. }
  1015. if (gl) {
  1016. if (!noFlush) {
  1017. flush();
  1018. }
  1019. }
  1020. else {
  1021. return false;
  1022. }
  1023. gl.enable(gl.BLEND);
  1024. // gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  1025. gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  1026. gl.disable(gl.DEPTH_TEST);
  1027. // gl.depthMask(gl.FALSE);
  1028. gl.depthFunc(gl.LESS);
  1029. shader = GLShader(gl); // eslint-disable-line new-cap
  1030. if (!shader) {
  1031. // We need to abort, there's no shader context
  1032. return false;
  1033. }
  1034. vbuffer = GLVertexBuffer(gl, shader); // eslint-disable-line new-cap
  1035. /**
  1036. * @private
  1037. */
  1038. function createTexture(name, fn) {
  1039. var props = {
  1040. isReady: false,
  1041. texture: doc.createElement('canvas'),
  1042. handle: gl.createTexture()
  1043. }, ctx = props.texture.getContext('2d');
  1044. textureHandles[name] = props;
  1045. props.texture.width = 512;
  1046. props.texture.height = 512;
  1047. ctx.mozImageSmoothingEnabled = false;
  1048. ctx.webkitImageSmoothingEnabled = false;
  1049. ctx.msImageSmoothingEnabled = false;
  1050. ctx.imageSmoothingEnabled = false;
  1051. ctx.strokeStyle = 'rgba(255, 255, 255, 0)';
  1052. ctx.fillStyle = '#FFF';
  1053. fn(ctx);
  1054. try {
  1055. gl.activeTexture(gl.TEXTURE0);
  1056. gl.bindTexture(gl.TEXTURE_2D, props.handle);
  1057. // gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
  1058. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, props.texture);
  1059. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  1063. // gl.generateMipmap(gl.TEXTURE_2D);
  1064. gl.bindTexture(gl.TEXTURE_2D, null);
  1065. props.isReady = true;
  1066. }
  1067. catch (e) {
  1068. // silent error
  1069. }
  1070. }
  1071. // Circle shape
  1072. createTexture('circle', function (ctx) {
  1073. ctx.beginPath();
  1074. ctx.arc(256, 256, 256, 0, 2 * Math.PI);
  1075. ctx.stroke();
  1076. ctx.fill();
  1077. });
  1078. // Square shape
  1079. createTexture('square', function (ctx) {
  1080. ctx.fillRect(0, 0, 512, 512);
  1081. });
  1082. // Diamond shape
  1083. createTexture('diamond', function (ctx) {
  1084. ctx.beginPath();
  1085. ctx.moveTo(256, 0);
  1086. ctx.lineTo(512, 256);
  1087. ctx.lineTo(256, 512);
  1088. ctx.lineTo(0, 256);
  1089. ctx.lineTo(256, 0);
  1090. ctx.fill();
  1091. });
  1092. // Triangle shape
  1093. createTexture('triangle', function (ctx) {
  1094. ctx.beginPath();
  1095. ctx.moveTo(0, 512);
  1096. ctx.lineTo(256, 0);
  1097. ctx.lineTo(512, 512);
  1098. ctx.lineTo(0, 512);
  1099. ctx.fill();
  1100. });
  1101. // Triangle shape (rotated)
  1102. createTexture('triangle-down', function (ctx) {
  1103. ctx.beginPath();
  1104. ctx.moveTo(0, 0);
  1105. ctx.lineTo(256, 512);
  1106. ctx.lineTo(512, 0);
  1107. ctx.lineTo(0, 0);
  1108. ctx.fill();
  1109. });
  1110. isInited = true;
  1111. if (settings.debug.timeSetup) {
  1112. console.timeEnd('gl setup'); // eslint-disable-line no-console
  1113. }
  1114. return true;
  1115. }
  1116. /**
  1117. * Check if we have a valid OGL context
  1118. * @private
  1119. * @returns {Boolean} - true if the context is valid
  1120. */
  1121. function valid() {
  1122. return gl !== false;
  1123. }
  1124. /**
  1125. * Check if the renderer has been initialized
  1126. * @private
  1127. * @returns {Boolean} - true if it has, false if not
  1128. */
  1129. function inited() {
  1130. return isInited;
  1131. }
  1132. /**
  1133. * @private
  1134. */
  1135. function destroy() {
  1136. flush();
  1137. vbuffer.destroy();
  1138. shader.destroy();
  1139. if (gl) {
  1140. objectEach(textureHandles, function (texture) {
  1141. if (texture.handle) {
  1142. gl.deleteTexture(texture.handle);
  1143. }
  1144. });
  1145. gl.canvas.width = 1;
  1146. gl.canvas.height = 1;
  1147. }
  1148. }
  1149. // /////////////////////////////////////////////////////////////////////////
  1150. exports = {
  1151. allocateBufferForSingleSeries: allocateBufferForSingleSeries,
  1152. pushSeries: pushSeries,
  1153. setSize: setSize,
  1154. inited: inited,
  1155. setThreshold: setThreshold,
  1156. init: init,
  1157. render: renderWhenReady,
  1158. settings: settings,
  1159. valid: valid,
  1160. clear: clear,
  1161. flush: flush,
  1162. setXAxis: setXAxis,
  1163. setYAxis: setYAxis,
  1164. data: data,
  1165. gl: getGL,
  1166. allocateBuffer: allocateBuffer,
  1167. destroy: destroy,
  1168. setOptions: setOptions
  1169. };
  1170. return exports;
  1171. }
  1172. export default GLRenderer;