vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2304 lines
66 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. var Emitter = require('emitter-component');
  2. var util = require('../util');
  3. var Point3d = require('./Point3d');
  4. var Point2d = require('./Point2d');
  5. var Filter = require('./Filter');
  6. var Slider = require('./Slider');
  7. var StepNumber = require('./StepNumber');
  8. var Settings = require('./Settings');
  9. var DataGroup = require('./DataGroup');
  10. /// enumerate the available styles
  11. Graph3d.STYLE = Settings.STYLE;
  12. /**
  13. * Following label is used in the settings to describe values which should be
  14. * determined by the code while running, from the current data and graph style.
  15. *
  16. * Using 'undefined' directly achieves the same thing, but this is more
  17. * descriptive by describing the intent.
  18. */
  19. var autoByDefault = undefined;
  20. /**
  21. * Default values for option settings.
  22. *
  23. * These are the values used when a Graph3d instance is initialized without
  24. * custom settings.
  25. *
  26. * If a field is not in this list, a default value of 'autoByDefault' is assumed,
  27. * which is just an alias for 'undefined'.
  28. */
  29. var DEFAULTS = {
  30. width : '400px',
  31. height : '400px',
  32. filterLabel : 'time',
  33. legendLabel : 'value',
  34. xLabel : 'x',
  35. yLabel : 'y',
  36. zLabel : 'z',
  37. xValueLabel : function(v) { return v; },
  38. yValueLabel : function(v) { return v; },
  39. zValueLabel : function(v) { return v; },
  40. showXAxis : true,
  41. showYAxis : true,
  42. showZAxis : true,
  43. showGrid : true,
  44. showPerspective : true,
  45. showShadow : false,
  46. keepAspectRatio : true,
  47. verticalRatio : 0.5, // 0.1 to 1.0, where 1.0 results in a 'cube'
  48. dotSizeRatio : 0.02, // size of the dots as a fraction of the graph width
  49. dotSizeMinFraction: 0.5, // size of min-value dot as a fraction of dotSizeRatio
  50. dotSizeMaxFraction: 2.5, // size of max-value dot as a fraction of dotSizeRatio
  51. showAnimationControls: autoByDefault,
  52. animationInterval : 1000, // milliseconds
  53. animationPreload : false,
  54. animationAutoStart : autoByDefault,
  55. axisColor : '#4D4D4D',
  56. gridColor : '#D3D3D3',
  57. xCenter : '55%',
  58. yCenter : '50%',
  59. style : Graph3d.STYLE.DOT,
  60. tooltip : false,
  61. tooltipStyle : {
  62. content : {
  63. padding : '10px',
  64. border : '1px solid #4d4d4d',
  65. color : '#1a1a1a',
  66. background : 'rgba(255,255,255,0.7)',
  67. borderRadius : '2px',
  68. boxShadow : '5px 5px 10px rgba(128,128,128,0.5)'
  69. },
  70. line : {
  71. height : '40px',
  72. width : '0',
  73. borderLeft : '1px solid #4d4d4d'
  74. },
  75. dot : {
  76. height : '0',
  77. width : '0',
  78. border : '5px solid #4d4d4d',
  79. borderRadius : '5px'
  80. }
  81. },
  82. showLegend : autoByDefault, // determined by graph style
  83. backgroundColor : autoByDefault,
  84. dataColor : {
  85. fill : '#7DC1FF',
  86. stroke : '#3267D2',
  87. strokeWidth: 1 // px
  88. },
  89. cameraPosition : {
  90. horizontal: 1.0,
  91. vertical : 0.5,
  92. distance : 1.7
  93. },
  94. xBarWidth : autoByDefault,
  95. yBarWidth : autoByDefault,
  96. valueMin : autoByDefault,
  97. valueMax : autoByDefault,
  98. xMin : autoByDefault,
  99. xMax : autoByDefault,
  100. xStep : autoByDefault,
  101. yMin : autoByDefault,
  102. yMax : autoByDefault,
  103. yStep : autoByDefault,
  104. zMin : autoByDefault,
  105. zMax : autoByDefault,
  106. zStep : autoByDefault
  107. };
  108. // -----------------------------------------------------------------------------
  109. // Class Graph3d
  110. // -----------------------------------------------------------------------------
  111. /**
  112. * @constructor Graph3d
  113. * Graph3d displays data in 3d.
  114. *
  115. * Graph3d is developed in javascript as a Google Visualization Chart.
  116. *
  117. * @param {Element} container The DOM element in which the Graph3d will
  118. * be created. Normally a div element.
  119. * @param {DataSet | DataView | Array} [data]
  120. * @param {Object} [options]
  121. */
  122. function Graph3d(container, data, options) {
  123. if (!(this instanceof Graph3d)) {
  124. throw new SyntaxError('Constructor must be called with the new operator');
  125. }
  126. // create variables and set default values
  127. this.containerElement = container;
  128. this.dataGroup = new DataGroup();
  129. this.dataPoints = null; // The table with point objects
  130. // create a frame and canvas
  131. this.create();
  132. Settings.setDefaults(DEFAULTS, this);
  133. // the column indexes
  134. this.colX = undefined;
  135. this.colY = undefined;
  136. this.colZ = undefined;
  137. this.colValue = undefined;
  138. this.colFilter = undefined;
  139. // TODO: customize axis range
  140. // apply options (also when undefined)
  141. this.setOptions(options);
  142. // apply data
  143. this.setData(data);
  144. }
  145. // Extend Graph3d with an Emitter mixin
  146. Emitter(Graph3d.prototype);
  147. /**
  148. * Calculate the scaling values, dependent on the range in x, y, and z direction
  149. */
  150. Graph3d.prototype._setScale = function() {
  151. this.scale = new Point3d(
  152. 1 / this.xRange.range(),
  153. 1 / this.yRange.range(),
  154. 1 / this.zRange.range()
  155. );
  156. // keep aspect ration between x and y scale if desired
  157. if (this.keepAspectRatio) {
  158. if (this.scale.x < this.scale.y) {
  159. //noinspection JSSuspiciousNameCombination
  160. this.scale.y = this.scale.x;
  161. }
  162. else {
  163. //noinspection JSSuspiciousNameCombination
  164. this.scale.x = this.scale.y;
  165. }
  166. }
  167. // scale the vertical axis
  168. this.scale.z *= this.verticalRatio;
  169. // TODO: can this be automated? verticalRatio?
  170. // determine scale for (optional) value
  171. if (this.valueRange !== undefined) {
  172. this.scale.value = 1 / this.valueRange.range();
  173. }
  174. // position the camera arm
  175. var xCenter = this.xRange.center() * this.scale.x;
  176. var yCenter = this.yRange.center() * this.scale.y;
  177. var zCenter = this.zRange.center() * this.scale.z;
  178. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  179. };
  180. /**
  181. * Convert a 3D location to a 2D location on screen
  182. * Source: ttp://en.wikipedia.org/wiki/3D_projection
  183. *
  184. * @param {Point3d} point3d A 3D point with parameters x, y, z
  185. * @returns {Point2d} point2d A 2D point with parameters x, y
  186. */
  187. Graph3d.prototype._convert3Dto2D = function(point3d) {
  188. var translation = this._convertPointToTranslation(point3d);
  189. return this._convertTranslationToScreen(translation);
  190. };
  191. /**
  192. * Convert a 3D location its translation seen from the camera
  193. * Source: http://en.wikipedia.org/wiki/3D_projection
  194. *
  195. * @param {Point3d} point3d A 3D point with parameters x, y, z
  196. * @returns {Point3d} translation A 3D point with parameters x, y, z This is
  197. * the translation of the point, seen from the
  198. * camera.
  199. */
  200. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  201. var cameraLocation = this.camera.getCameraLocation(),
  202. cameraRotation = this.camera.getCameraRotation(),
  203. ax = point3d.x * this.scale.x,
  204. ay = point3d.y * this.scale.y,
  205. az = point3d.z * this.scale.z,
  206. cx = cameraLocation.x,
  207. cy = cameraLocation.y,
  208. cz = cameraLocation.z,
  209. // calculate angles
  210. sinTx = Math.sin(cameraRotation.x),
  211. cosTx = Math.cos(cameraRotation.x),
  212. sinTy = Math.sin(cameraRotation.y),
  213. cosTy = Math.cos(cameraRotation.y),
  214. sinTz = Math.sin(cameraRotation.z),
  215. cosTz = Math.cos(cameraRotation.z),
  216. // calculate translation
  217. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  218. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  219. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  220. return new Point3d(dx, dy, dz);
  221. };
  222. /**
  223. * Convert a translation point to a point on the screen
  224. *
  225. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  226. * the translation of the point, seen from the
  227. * camera.
  228. * @returns {Point2d} point2d A 2D point with parameters x, y
  229. */
  230. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  231. var ex = this.eye.x,
  232. ey = this.eye.y,
  233. ez = this.eye.z,
  234. dx = translation.x,
  235. dy = translation.y,
  236. dz = translation.z;
  237. // calculate position on screen from translation
  238. var bx;
  239. var by;
  240. if (this.showPerspective) {
  241. bx = (dx - ex) * (ez / dz);
  242. by = (dy - ey) * (ez / dz);
  243. }
  244. else {
  245. bx = dx * -(ez / this.camera.getArmLength());
  246. by = dy * -(ez / this.camera.getArmLength());
  247. }
  248. // shift and scale the point to the center of the screen
  249. // use the width of the graph to scale both horizontally and vertically.
  250. return new Point2d(
  251. this.currentXCenter + bx * this.frame.canvas.clientWidth,
  252. this.currentYCenter - by * this.frame.canvas.clientWidth);
  253. };
  254. /**
  255. * Calculate the translations and screen positions of all points
  256. */
  257. Graph3d.prototype._calcTranslations = function(points) {
  258. for (var i = 0; i < points.length; i++) {
  259. var point = points[i];
  260. point.trans = this._convertPointToTranslation(point.point);
  261. point.screen = this._convertTranslationToScreen(point.trans);
  262. // calculate the translation of the point at the bottom (needed for sorting)
  263. var transBottom = this._convertPointToTranslation(point.bottom);
  264. point.dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  265. }
  266. // sort the points on depth of their (x,y) position (not on z)
  267. var sortDepth = function (a, b) {
  268. return b.dist - a.dist;
  269. };
  270. points.sort(sortDepth);
  271. };
  272. /**
  273. * Check if the state is consistent for the use of the value field.
  274. *
  275. * Throws if a problem is detected.
  276. */
  277. Graph3d.prototype._checkValueField = function (data) {
  278. var hasValueField = this.style === Graph3d.STYLE.BARCOLOR
  279. || this.style === Graph3d.STYLE.BARSIZE
  280. || this.style === Graph3d.STYLE.DOTCOLOR
  281. || this.style === Graph3d.STYLE.DOTSIZE;
  282. if (!hasValueField) {
  283. return; // No need to check further
  284. }
  285. // Following field must be present for the current graph style
  286. if (this.colValue === undefined) {
  287. throw new Error('Expected data to have '
  288. + ' field \'style\' '
  289. + ' for graph style \'' + this.style + '\''
  290. );
  291. }
  292. // The data must also contain this field.
  293. // Note that only first data element is checked.
  294. if (data[0][this.colValue] === undefined) {
  295. throw new Error('Expected data to have '
  296. + ' field \'' + this.colValue + '\' '
  297. + ' for graph style \'' + this.style + '\''
  298. );
  299. }
  300. };
  301. Graph3d.prototype._initializeData = function(rawData, style) {
  302. this.dataGroup.initializeData(this, rawData, style);
  303. // Transfer min/max values to the Graph3d instance.
  304. // TODO: later on, all min/maxes of all datagroups will be combined here
  305. this.xRange = this.dataGroup.xRange;
  306. this.yRange = this.dataGroup.yRange;
  307. this.zRange = this.dataGroup.zRange;
  308. this.valueRange = this.dataGroup.valueRange;
  309. // Values currently needed but which need to be sorted out for
  310. // the multiple graph case.
  311. this.xStep = this.dataGroup.xStep;
  312. this.yStep = this.dataGroup.yStep;
  313. this.zStep = this.dataGroup.zStep;
  314. this.xBarWidth = this.dataGroup.xBarWidth;
  315. this.yBarWidth = this.dataGroup.yBarWidth;
  316. this.colX = this.dataGroup.colX;
  317. this.colY = this.dataGroup.colY;
  318. this.colZ = this.dataGroup.colZ;
  319. this.colValue = this.dataGroup.colValue;
  320. // Check if a filter column is provided
  321. var data = this.dataGroup.getDataTable();
  322. if (data[0].hasOwnProperty('filter')) {
  323. // Only set this field if it's actually present
  324. this.colFilter = 'filter';
  325. var me = this;
  326. if (this.dataFilter === undefined) {
  327. this.dataFilter = new Filter(this.dataGroup, this.colFilter, this);
  328. this.dataFilter.setOnLoadCallback(function() {me.redraw();});
  329. }
  330. }
  331. // set the scale dependent on the ranges.
  332. this._setScale();
  333. };
  334. /**
  335. * Return all data values as a list of Point3d objects
  336. */
  337. Graph3d.prototype.getDataPoints = function(data) {
  338. var dataPoints = [];
  339. for (var i = 0; i < data.length; i++) {
  340. var point = new Point3d();
  341. point.x = data[i][this.colX] || 0;
  342. point.y = data[i][this.colY] || 0;
  343. point.z = data[i][this.colZ] || 0;
  344. point.data = data[i];
  345. if (this.colValue !== undefined) {
  346. point.value = data[i][this.colValue] || 0;
  347. }
  348. var obj = {};
  349. obj.point = point;
  350. obj.bottom = new Point3d(point.x, point.y, this.zRange.min);
  351. obj.trans = undefined;
  352. obj.screen = undefined;
  353. dataPoints.push(obj);
  354. }
  355. return dataPoints;
  356. };
  357. /**
  358. * Filter the data based on the current filter
  359. *
  360. * @param {Array} data
  361. * @returns {Array} dataPoints Array with point objects which can be drawn on
  362. * screen
  363. */
  364. Graph3d.prototype._getDataPoints = function (data) {
  365. // TODO: store the created matrix dataPoints in the filters instead of
  366. // reloading each time.
  367. var x, y, i, obj;
  368. var dataPoints = [];
  369. if (this.style === Graph3d.STYLE.GRID ||
  370. this.style === Graph3d.STYLE.SURFACE) {
  371. // copy all values from the data table to a matrix
  372. // the provided values are supposed to form a grid of (x,y) positions
  373. // create two lists with all present x and y values
  374. var dataX = this.dataGroup.getDistinctValues(this.colX, data);
  375. var dataY = this.dataGroup.getDistinctValues(this.colY, data);
  376. dataPoints = this.getDataPoints(data);
  377. // create a grid, a 2d matrix, with all values.
  378. var dataMatrix = []; // temporary data matrix
  379. for (i = 0; i < dataPoints.length; i++) {
  380. obj = dataPoints[i];
  381. // TODO: implement Array().indexOf() for Internet Explorer
  382. var xIndex = dataX.indexOf(obj.point.x);
  383. var yIndex = dataY.indexOf(obj.point.y);
  384. if (dataMatrix[xIndex] === undefined) {
  385. dataMatrix[xIndex] = [];
  386. }
  387. dataMatrix[xIndex][yIndex] = obj;
  388. }
  389. // fill in the pointers to the neighbors.
  390. for (x = 0; x < dataMatrix.length; x++) {
  391. for (y = 0; y < dataMatrix[x].length; y++) {
  392. if (dataMatrix[x][y]) {
  393. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  394. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  395. dataMatrix[x][y].pointCross =
  396. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  397. dataMatrix[x+1][y+1] :
  398. undefined;
  399. }
  400. }
  401. }
  402. }
  403. else { // 'dot', 'dot-line', etc.
  404. this._checkValueField(data);
  405. dataPoints = this.getDataPoints(data);
  406. if (this.style === Graph3d.STYLE.LINE) {
  407. // Add next member points for line drawing
  408. for (i = 0; i < dataPoints.length; i++) {
  409. if (i > 0) {
  410. dataPoints[i - 1].pointNext = dataPoints[i];
  411. }
  412. }
  413. }
  414. }
  415. return dataPoints;
  416. };
  417. /**
  418. * Create the main frame for the Graph3d.
  419. *
  420. * This function is executed once when a Graph3d object is created. The frame
  421. * contains a canvas, and this canvas contains all objects like the axis and
  422. * nodes.
  423. */
  424. Graph3d.prototype.create = function () {
  425. // remove all elements from the container element.
  426. while (this.containerElement.hasChildNodes()) {
  427. this.containerElement.removeChild(this.containerElement.firstChild);
  428. }
  429. this.frame = document.createElement('div');
  430. this.frame.style.position = 'relative';
  431. this.frame.style.overflow = 'hidden';
  432. // create the graph canvas (HTML canvas element)
  433. this.frame.canvas = document.createElement( 'canvas' );
  434. this.frame.canvas.style.position = 'relative';
  435. this.frame.appendChild(this.frame.canvas);
  436. //if (!this.frame.canvas.getContext) {
  437. {
  438. var noCanvas = document.createElement( 'DIV' );
  439. noCanvas.style.color = 'red';
  440. noCanvas.style.fontWeight = 'bold' ;
  441. noCanvas.style.padding = '10px';
  442. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  443. this.frame.canvas.appendChild(noCanvas);
  444. }
  445. this.frame.filter = document.createElement( 'div' );
  446. this.frame.filter.style.position = 'absolute';
  447. this.frame.filter.style.bottom = '0px';
  448. this.frame.filter.style.left = '0px';
  449. this.frame.filter.style.width = '100%';
  450. this.frame.appendChild(this.frame.filter);
  451. // add event listeners to handle moving and zooming the contents
  452. var me = this;
  453. var onmousedown = function (event) {me._onMouseDown(event);};
  454. var ontouchstart = function (event) {me._onTouchStart(event);};
  455. var onmousewheel = function (event) {me._onWheel(event);};
  456. var ontooltip = function (event) {me._onTooltip(event);};
  457. var onclick = function(event) {me._onClick(event);};
  458. // TODO: these events are never cleaned up... can give a 'memory leakage'
  459. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  460. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  461. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  462. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  463. util.addEventListener(this.frame.canvas, 'click', onclick);
  464. // add the new graph to the container element
  465. this.containerElement.appendChild(this.frame);
  466. };
  467. /**
  468. * Set a new size for the graph
  469. */
  470. Graph3d.prototype._setSize = function(width, height) {
  471. this.frame.style.width = width;
  472. this.frame.style.height = height;
  473. this._resizeCanvas();
  474. };
  475. /**
  476. * Resize the canvas to the current size of the frame
  477. */
  478. Graph3d.prototype._resizeCanvas = function() {
  479. this.frame.canvas.style.width = '100%';
  480. this.frame.canvas.style.height = '100%';
  481. this.frame.canvas.width = this.frame.canvas.clientWidth;
  482. this.frame.canvas.height = this.frame.canvas.clientHeight;
  483. // adjust with for margin
  484. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  485. };
  486. /**
  487. * Start animation
  488. */
  489. Graph3d.prototype.animationStart = function() {
  490. if (!this.frame.filter || !this.frame.filter.slider)
  491. throw new Error('No animation available');
  492. this.frame.filter.slider.play();
  493. };
  494. /**
  495. * Stop animation
  496. */
  497. Graph3d.prototype.animationStop = function() {
  498. if (!this.frame.filter || !this.frame.filter.slider) return;
  499. this.frame.filter.slider.stop();
  500. };
  501. /**
  502. * Resize the center position based on the current values in this.xCenter
  503. * and this.yCenter (which are strings with a percentage or a value
  504. * in pixels). The center positions are the variables this.currentXCenter
  505. * and this.currentYCenter
  506. */
  507. Graph3d.prototype._resizeCenter = function() {
  508. // calculate the horizontal center position
  509. if (this.xCenter.charAt(this.xCenter.length-1) === '%') {
  510. this.currentXCenter =
  511. parseFloat(this.xCenter) / 100 *
  512. this.frame.canvas.clientWidth;
  513. }
  514. else {
  515. this.currentXCenter = parseFloat(this.xCenter); // supposed to be in px
  516. }
  517. // calculate the vertical center position
  518. if (this.yCenter.charAt(this.yCenter.length-1) === '%') {
  519. this.currentYCenter =
  520. parseFloat(this.yCenter) / 100 *
  521. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  522. }
  523. else {
  524. this.currentYCenter = parseFloat(this.yCenter); // supposed to be in px
  525. }
  526. };
  527. /**
  528. * Retrieve the current camera rotation
  529. *
  530. * @returns {object} An object with parameters horizontal, vertical, and
  531. * distance
  532. */
  533. Graph3d.prototype.getCameraPosition = function() {
  534. var pos = this.camera.getArmRotation();
  535. pos.distance = this.camera.getArmLength();
  536. return pos;
  537. };
  538. /**
  539. * Load data into the 3D Graph
  540. */
  541. Graph3d.prototype._readData = function(data) {
  542. // read the data
  543. this._initializeData(data, this.style);
  544. if (this.dataFilter) {
  545. // apply filtering
  546. this.dataPoints = this.dataFilter._getDataPoints();
  547. }
  548. else {
  549. // no filtering. load all data
  550. this.dataPoints = this._getDataPoints(this.dataGroup.getDataTable());
  551. }
  552. // draw the filter
  553. this._redrawFilter();
  554. };
  555. /**
  556. * Replace the dataset of the Graph3d
  557. *
  558. * @param {Array | DataSet | DataView} data
  559. */
  560. Graph3d.prototype.setData = function (data) {
  561. if (data === undefined || data === null) return;
  562. this._readData(data);
  563. this.redraw();
  564. // start animation when option is true
  565. if (this.animationAutoStart && this.dataFilter) {
  566. this.animationStart();
  567. }
  568. };
  569. /**
  570. * Update the options. Options will be merged with current options
  571. *
  572. * @param {Object} options
  573. */
  574. Graph3d.prototype.setOptions = function (options) {
  575. this.animationStop();
  576. Settings.setOptions(options, this);
  577. this.setPointDrawingMethod();
  578. this._setSize(this.width, this.height);
  579. this.setData(this.dataGroup.getDataTable());
  580. // start animation when option is true
  581. if (this.animationAutoStart && this.dataFilter) {
  582. this.animationStart();
  583. }
  584. };
  585. /**
  586. * Determine which point drawing method to use for the current graph style.
  587. */
  588. Graph3d.prototype.setPointDrawingMethod = function() {
  589. var method = undefined;
  590. switch (this.style) {
  591. case Graph3d.STYLE.BAR:
  592. method = Graph3d.prototype._redrawBarGraphPoint;
  593. break;
  594. case Graph3d.STYLE.BARCOLOR:
  595. method = Graph3d.prototype._redrawBarColorGraphPoint;
  596. break;
  597. case Graph3d.STYLE.BARSIZE:
  598. method = Graph3d.prototype._redrawBarSizeGraphPoint;
  599. break;
  600. case Graph3d.STYLE.DOT:
  601. method = Graph3d.prototype._redrawDotGraphPoint;
  602. break;
  603. case Graph3d.STYLE.DOTLINE:
  604. method = Graph3d.prototype._redrawDotLineGraphPoint;
  605. break;
  606. case Graph3d.STYLE.DOTCOLOR:
  607. method = Graph3d.prototype._redrawDotColorGraphPoint;
  608. break;
  609. case Graph3d.STYLE.DOTSIZE:
  610. method = Graph3d.prototype._redrawDotSizeGraphPoint;
  611. break;
  612. case Graph3d.STYLE.SURFACE:
  613. method = Graph3d.prototype._redrawSurfaceGraphPoint;
  614. break;
  615. case Graph3d.STYLE.GRID:
  616. method = Graph3d.prototype._redrawGridGraphPoint;
  617. break;
  618. case Graph3d.STYLE.LINE:
  619. method = Graph3d.prototype._redrawLineGraphPoint;
  620. break;
  621. default:
  622. throw new Error('Can not determine point drawing method '
  623. + 'for graph style \'' + this.style + '\'');
  624. }
  625. this._pointDrawingMethod = method;
  626. };
  627. /**
  628. * Redraw the Graph.
  629. */
  630. Graph3d.prototype.redraw = function() {
  631. if (this.dataPoints === undefined) {
  632. throw new Error('Graph data not initialized');
  633. }
  634. this._resizeCanvas();
  635. this._resizeCenter();
  636. this._redrawSlider();
  637. this._redrawClear();
  638. this._redrawAxis();
  639. this._redrawDataGraph();
  640. this._redrawInfo();
  641. this._redrawLegend();
  642. };
  643. /**
  644. * Get drawing context without exposing canvas
  645. */
  646. Graph3d.prototype._getContext = function() {
  647. var canvas = this.frame.canvas;
  648. var ctx = canvas.getContext('2d');
  649. ctx.lineJoin = 'round';
  650. ctx.lineCap = 'round';
  651. return ctx;
  652. };
  653. /**
  654. * Clear the canvas before redrawing
  655. */
  656. Graph3d.prototype._redrawClear = function() {
  657. var canvas = this.frame.canvas;
  658. var ctx = canvas.getContext('2d');
  659. ctx.clearRect(0, 0, canvas.width, canvas.height);
  660. };
  661. Graph3d.prototype._dotSize = function() {
  662. return this.frame.clientWidth * this.dotSizeRatio;
  663. };
  664. /**
  665. * Get legend width
  666. */
  667. Graph3d.prototype._getLegendWidth = function() {
  668. var width;
  669. if (this.style === Graph3d.STYLE.DOTSIZE) {
  670. var dotSize = this._dotSize();
  671. //width = dotSize / 2 + dotSize * 2;
  672. width = dotSize * this.dotSizeMaxFraction;
  673. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  674. width = this.xBarWidth ;
  675. } else {
  676. width = 20;
  677. }
  678. return width;
  679. }
  680. /**
  681. * Redraw the legend based on size, dot color, or surface height
  682. */
  683. Graph3d.prototype._redrawLegend = function() {
  684. //Return without drawing anything, if no legend is specified
  685. if (this.showLegend !== true) {
  686. return;
  687. }
  688. // Do not draw legend when graph style does not support
  689. if (this.style === Graph3d.STYLE.LINE
  690. || this.style === Graph3d.STYLE.BARSIZE //TODO add legend support for BARSIZE
  691. ){
  692. return;
  693. }
  694. // Legend types - size and color. Determine if size legend.
  695. var isSizeLegend = (this.style === Graph3d.STYLE.BARSIZE
  696. || this.style === Graph3d.STYLE.DOTSIZE) ;
  697. // Legend is either tracking z values or style values. This flag if false means use z values.
  698. var isValueLegend = (this.style === Graph3d.STYLE.DOTSIZE
  699. || this.style === Graph3d.STYLE.DOTCOLOR
  700. || this.style === Graph3d.STYLE.BARCOLOR);
  701. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  702. var top = this.margin;
  703. var width = this._getLegendWidth() ; // px - overwritten by size legend
  704. var right = this.frame.clientWidth - this.margin;
  705. var left = right - width;
  706. var bottom = top + height;
  707. var ctx = this._getContext();
  708. ctx.lineWidth = 1;
  709. ctx.font = '14px arial'; // TODO: put in options
  710. if (isSizeLegend === false) {
  711. // draw the color bar
  712. var ymin = 0;
  713. var ymax = height; // Todo: make height customizable
  714. var y;
  715. for (y = ymin; y < ymax; y++) {
  716. var f = (y - ymin) / (ymax - ymin);
  717. var hue = f * 240;
  718. var color = this._hsv2rgb(hue, 1, 1);
  719. ctx.strokeStyle = color;
  720. ctx.beginPath();
  721. ctx.moveTo(left, top + y);
  722. ctx.lineTo(right, top + y);
  723. ctx.stroke();
  724. }
  725. ctx.strokeStyle = this.axisColor;
  726. ctx.strokeRect(left, top, width, height);
  727. } else {
  728. // draw the size legend box
  729. var widthMin;
  730. if (this.style === Graph3d.STYLE.DOTSIZE) {
  731. // Get the proportion to max and min right
  732. widthMin = width * (this.dotSizeMinFraction / this.dotSizeMaxFraction);
  733. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  734. //widthMin = this.xBarWidth * 0.2 this is wrong - barwidth measures in terms of xvalues
  735. }
  736. ctx.strokeStyle = this.axisColor;
  737. ctx.fillStyle = this.dataColor.fill;
  738. ctx.beginPath();
  739. ctx.moveTo(left, top);
  740. ctx.lineTo(right, top);
  741. ctx.lineTo(left + widthMin, bottom);
  742. ctx.lineTo(left, bottom);
  743. ctx.closePath();
  744. ctx.fill();
  745. ctx.stroke();
  746. }
  747. // print value text along the legend edge
  748. var gridLineLen = 5; // px
  749. var legendMin = isValueLegend ? this.valueRange.min : this.zRange.min;
  750. var legendMax = isValueLegend ? this.valueRange.max : this.zRange.max;
  751. var step = new StepNumber(legendMin, legendMax, (legendMax-legendMin)/5, true);
  752. step.start(true);
  753. var from;
  754. var to;
  755. while (!step.end()) {
  756. y = bottom - (step.getCurrent() - legendMin) / (legendMax - legendMin) * height;
  757. from = new Point2d(left - gridLineLen, y);
  758. to = new Point2d(left, y);
  759. this._line(ctx, from, to);
  760. ctx.textAlign = 'right';
  761. ctx.textBaseline = 'middle';
  762. ctx.fillStyle = this.axisColor;
  763. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  764. step.next();
  765. }
  766. ctx.textAlign = 'right';
  767. ctx.textBaseline = 'top';
  768. var label = this.legendLabel;
  769. ctx.fillText(label, right, bottom + this.margin);
  770. };
  771. /**
  772. * Redraw the filter
  773. */
  774. Graph3d.prototype._redrawFilter = function() {
  775. this.frame.filter.innerHTML = '';
  776. if (this.dataFilter) {
  777. var options = {
  778. 'visible': this.showAnimationControls
  779. };
  780. var slider = new Slider(this.frame.filter, options);
  781. this.frame.filter.slider = slider;
  782. // TODO: css here is not nice here...
  783. this.frame.filter.style.padding = '10px';
  784. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  785. slider.setValues(this.dataFilter.values);
  786. slider.setPlayInterval(this.animationInterval);
  787. // create an event handler
  788. var me = this;
  789. var onchange = function () {
  790. var index = slider.getIndex();
  791. me.dataFilter.selectValue(index);
  792. me.dataPoints = me.dataFilter._getDataPoints();
  793. me.redraw();
  794. };
  795. slider.setOnChangeCallback(onchange);
  796. }
  797. else {
  798. this.frame.filter.slider = undefined;
  799. }
  800. };
  801. /**
  802. * Redraw the slider
  803. */
  804. Graph3d.prototype._redrawSlider = function() {
  805. if ( this.frame.filter.slider !== undefined) {
  806. this.frame.filter.slider.redraw();
  807. }
  808. };
  809. /**
  810. * Redraw common information
  811. */
  812. Graph3d.prototype._redrawInfo = function() {
  813. if (this.dataFilter) {
  814. var ctx = this._getContext();
  815. ctx.font = '14px arial'; // TODO: put in options
  816. ctx.lineStyle = 'gray';
  817. ctx.fillStyle = 'gray';
  818. ctx.textAlign = 'left';
  819. ctx.textBaseline = 'top';
  820. var x = this.margin;
  821. var y = this.margin;
  822. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  823. }
  824. };
  825. /**
  826. * Draw a line between 2d points 'from' and 'to'.
  827. *
  828. * If stroke style specified, set that as well.
  829. */
  830. Graph3d.prototype._line = function(ctx, from, to, strokeStyle) {
  831. if (strokeStyle !== undefined) {
  832. ctx.strokeStyle = strokeStyle;
  833. }
  834. ctx.beginPath();
  835. ctx.moveTo(from.x, from.y);
  836. ctx.lineTo(to.x , to.y );
  837. ctx.stroke();
  838. }
  839. Graph3d.prototype.drawAxisLabelX = function(ctx, point3d, text, armAngle, yMargin) {
  840. if (yMargin === undefined) {
  841. yMargin = 0;
  842. }
  843. var point2d = this._convert3Dto2D(point3d);
  844. if (Math.cos(armAngle * 2) > 0) {
  845. ctx.textAlign = 'center';
  846. ctx.textBaseline = 'top';
  847. point2d.y += yMargin;
  848. }
  849. else if (Math.sin(armAngle * 2) < 0){
  850. ctx.textAlign = 'right';
  851. ctx.textBaseline = 'middle';
  852. }
  853. else {
  854. ctx.textAlign = 'left';
  855. ctx.textBaseline = 'middle';
  856. }
  857. ctx.fillStyle = this.axisColor;
  858. ctx.fillText(text, point2d.x, point2d.y);
  859. }
  860. Graph3d.prototype.drawAxisLabelY = function(ctx, point3d, text, armAngle, yMargin) {
  861. if (yMargin === undefined) {
  862. yMargin = 0;
  863. }
  864. var point2d = this._convert3Dto2D(point3d);
  865. if (Math.cos(armAngle * 2) < 0) {
  866. ctx.textAlign = 'center';
  867. ctx.textBaseline = 'top';
  868. point2d.y += yMargin;
  869. }
  870. else if (Math.sin(armAngle * 2) > 0){
  871. ctx.textAlign = 'right';
  872. ctx.textBaseline = 'middle';
  873. }
  874. else {
  875. ctx.textAlign = 'left';
  876. ctx.textBaseline = 'middle';
  877. }
  878. ctx.fillStyle = this.axisColor;
  879. ctx.fillText(text, point2d.x, point2d.y);
  880. }
  881. Graph3d.prototype.drawAxisLabelZ = function(ctx, point3d, text, offset) {
  882. if (offset === undefined) {
  883. offset = 0;
  884. }
  885. var point2d = this._convert3Dto2D(point3d);
  886. ctx.textAlign = 'right';
  887. ctx.textBaseline = 'middle';
  888. ctx.fillStyle = this.axisColor;
  889. ctx.fillText(text, point2d.x - offset, point2d.y);
  890. };
  891. /**
  892. /**
  893. * Draw a line between 2d points 'from' and 'to'.
  894. *
  895. * If stroke style specified, set that as well.
  896. */
  897. Graph3d.prototype._line3d = function(ctx, from, to, strokeStyle) {
  898. var from2d = this._convert3Dto2D(from);
  899. var to2d = this._convert3Dto2D(to);
  900. this._line(ctx, from2d, to2d, strokeStyle);
  901. }
  902. /**
  903. * Redraw the axis
  904. */
  905. Graph3d.prototype._redrawAxis = function() {
  906. var ctx = this._getContext(),
  907. from, to, step, prettyStep,
  908. text, xText, yText, zText,
  909. offset, xOffset, yOffset;
  910. // TODO: get the actual rendered style of the containerElement
  911. //ctx.font = this.containerElement.style.font;
  912. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  913. // calculate the length for the short grid lines
  914. var gridLenX = 0.025 / this.scale.x;
  915. var gridLenY = 0.025 / this.scale.y;
  916. var textMargin = 5 / this.camera.getArmLength(); // px
  917. var armAngle = this.camera.getArmRotation().horizontal;
  918. var armVector = new Point2d(Math.cos(armAngle), Math.sin(armAngle));
  919. var xRange = this.xRange;
  920. var yRange = this.yRange;
  921. var zRange = this.zRange;
  922. var point3d;
  923. // draw x-grid lines
  924. ctx.lineWidth = 1;
  925. prettyStep = (this.defaultXStep === undefined);
  926. step = new StepNumber(xRange.min, xRange.max, this.xStep, prettyStep);
  927. step.start(true);
  928. while (!step.end()) {
  929. var x = step.getCurrent();
  930. if (this.showGrid) {
  931. from = new Point3d(x, yRange.min, zRange.min);
  932. to = new Point3d(x, yRange.max, zRange.min);
  933. this._line3d(ctx, from, to, this.gridColor);
  934. }
  935. else if (this.showXAxis) {
  936. from = new Point3d(x, yRange.min, zRange.min);
  937. to = new Point3d(x, yRange.min+gridLenX, zRange.min);
  938. this._line3d(ctx, from, to, this.axisColor);
  939. from = new Point3d(x, yRange.max, zRange.min);
  940. to = new Point3d(x, yRange.max-gridLenX, zRange.min);
  941. this._line3d(ctx, from, to, this.axisColor);
  942. }
  943. if (this.showXAxis) {
  944. yText = (armVector.x > 0) ? yRange.min : yRange.max;
  945. point3d = new Point3d(x, yText, zRange.min);
  946. let msg = ' ' + this.xValueLabel(x) + ' ';
  947. this.drawAxisLabelX(ctx, point3d, msg, armAngle, textMargin);
  948. }
  949. step.next();
  950. }
  951. // draw y-grid lines
  952. ctx.lineWidth = 1;
  953. prettyStep = (this.defaultYStep === undefined);
  954. step = new StepNumber(yRange.min, yRange.max, this.yStep, prettyStep);
  955. step.start(true);
  956. while (!step.end()) {
  957. var y = step.getCurrent();
  958. if (this.showGrid) {
  959. from = new Point3d(xRange.min, y, zRange.min);
  960. to = new Point3d(xRange.max, y, zRange.min);
  961. this._line3d(ctx, from, to, this.gridColor);
  962. }
  963. else if (this.showYAxis){
  964. from = new Point3d(xRange.min, y, zRange.min);
  965. to = new Point3d(xRange.min+gridLenY, y, zRange.min);
  966. this._line3d(ctx, from, to, this.axisColor);
  967. from = new Point3d(xRange.max, y, zRange.min);
  968. to = new Point3d(xRange.max-gridLenY, y, zRange.min);
  969. this._line3d(ctx, from, to, this.axisColor);
  970. }
  971. if (this.showYAxis) {
  972. xText = (armVector.y > 0) ? xRange.min : xRange.max;
  973. point3d = new Point3d(xText, y, zRange.min);
  974. let msg = ' ' + this.yValueLabel(y) + ' ';
  975. this.drawAxisLabelY(ctx, point3d, msg, armAngle, textMargin);
  976. }
  977. step.next();
  978. }
  979. // draw z-grid lines and axis
  980. if (this.showZAxis) {
  981. ctx.lineWidth = 1;
  982. prettyStep = (this.defaultZStep === undefined);
  983. step = new StepNumber(zRange.min, zRange.max, this.zStep, prettyStep);
  984. step.start(true);
  985. xText = (armVector.x > 0) ? xRange.min : xRange.max;
  986. yText = (armVector.y < 0) ? yRange.min : yRange.max;
  987. while (!step.end()) {
  988. var z = step.getCurrent();
  989. // TODO: make z-grid lines really 3d?
  990. var from3d = new Point3d(xText, yText, z);
  991. var from2d = this._convert3Dto2D(from3d);
  992. to = new Point2d(from2d.x - textMargin, from2d.y);
  993. this._line(ctx, from2d, to, this.axisColor);
  994. let msg = this.zValueLabel(z) + ' ';
  995. this.drawAxisLabelZ(ctx, from3d, msg, 5);
  996. step.next();
  997. }
  998. ctx.lineWidth = 1;
  999. from = new Point3d(xText, yText, zRange.min);
  1000. to = new Point3d(xText, yText, zRange.max);
  1001. this._line3d(ctx, from, to, this.axisColor);
  1002. }
  1003. // draw x-axis
  1004. if (this.showXAxis) {
  1005. var xMin2d;
  1006. var xMax2d;
  1007. ctx.lineWidth = 1;
  1008. // line at yMin
  1009. xMin2d = new Point3d(xRange.min, yRange.min, zRange.min);
  1010. xMax2d = new Point3d(xRange.max, yRange.min, zRange.min);
  1011. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  1012. // line at ymax
  1013. xMin2d = new Point3d(xRange.min, yRange.max, zRange.min);
  1014. xMax2d = new Point3d(xRange.max, yRange.max, zRange.min);
  1015. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  1016. }
  1017. // draw y-axis
  1018. if (this.showYAxis) {
  1019. ctx.lineWidth = 1;
  1020. // line at xMin
  1021. from = new Point3d(xRange.min, yRange.min, zRange.min);
  1022. to = new Point3d(xRange.min, yRange.max, zRange.min);
  1023. this._line3d(ctx, from, to, this.axisColor);
  1024. // line at xMax
  1025. from = new Point3d(xRange.max, yRange.min, zRange.min);
  1026. to = new Point3d(xRange.max, yRange.max, zRange.min);
  1027. this._line3d(ctx, from, to, this.axisColor);
  1028. }
  1029. // draw x-label
  1030. var xLabel = this.xLabel;
  1031. if (xLabel.length > 0 && this.showXAxis) {
  1032. yOffset = 0.1 / this.scale.y;
  1033. xText = (xRange.max + 3*xRange.min)/4;
  1034. yText = (armVector.x > 0) ? yRange.min - yOffset: yRange.max + yOffset;
  1035. text = new Point3d(xText, yText, zRange.min);
  1036. this.drawAxisLabelX(ctx, text, xLabel, armAngle);
  1037. }
  1038. // draw y-label
  1039. var yLabel = this.yLabel;
  1040. if (yLabel.length > 0 && this.showYAxis) {
  1041. xOffset = 0.1 / this.scale.x;
  1042. xText = (armVector.y > 0) ? xRange.min - xOffset : xRange.max + xOffset;
  1043. yText = (yRange.max + 3*yRange.min)/4;
  1044. text = new Point3d(xText, yText, zRange.min);
  1045. this.drawAxisLabelY(ctx, text, yLabel, armAngle);
  1046. }
  1047. // draw z-label
  1048. var zLabel = this.zLabel;
  1049. if (zLabel.length > 0 && this.showZAxis) {
  1050. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  1051. xText = (armVector.x > 0) ? xRange.min : xRange.max;
  1052. yText = (armVector.y < 0) ? yRange.min : yRange.max;
  1053. zText = (zRange.max + 3*zRange.min)/4;
  1054. text = new Point3d(xText, yText, zText);
  1055. this.drawAxisLabelZ(ctx, text, zLabel, offset);
  1056. }
  1057. };
  1058. /**
  1059. * Calculate the color based on the given value.
  1060. * @param {Number} H Hue, a value be between 0 and 360
  1061. * @param {Number} S Saturation, a value between 0 and 1
  1062. * @param {Number} V Value, a value between 0 and 1
  1063. */
  1064. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  1065. var R, G, B, C, Hi, X;
  1066. C = V * S;
  1067. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  1068. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  1069. switch (Hi) {
  1070. case 0: R = C; G = X; B = 0; break;
  1071. case 1: R = X; G = C; B = 0; break;
  1072. case 2: R = 0; G = C; B = X; break;
  1073. case 3: R = 0; G = X; B = C; break;
  1074. case 4: R = X; G = 0; B = C; break;
  1075. case 5: R = C; G = 0; B = X; break;
  1076. default: R = 0; G = 0; B = 0; break;
  1077. }
  1078. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  1079. };
  1080. Graph3d.prototype._getStrokeWidth = function(point) {
  1081. if (point !== undefined) {
  1082. if (this.showPerspective) {
  1083. return 1 / -point.trans.z * this.dataColor.strokeWidth;
  1084. }
  1085. else {
  1086. return -(this.eye.z / this.camera.getArmLength()) * this.dataColor.strokeWidth;
  1087. }
  1088. }
  1089. return this.dataColor.strokeWidth;
  1090. };
  1091. // -----------------------------------------------------------------------------
  1092. // Drawing primitives for the graphs
  1093. // -----------------------------------------------------------------------------
  1094. /**
  1095. * Draw a bar element in the view with the given properties.
  1096. */
  1097. Graph3d.prototype._redrawBar = function(ctx, point, xWidth, yWidth, color, borderColor) {
  1098. var surface;
  1099. // calculate all corner points
  1100. var me = this;
  1101. var point3d = point.point;
  1102. var zMin = this.zRange.min;
  1103. var top = [
  1104. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  1105. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  1106. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  1107. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  1108. ];
  1109. var bottom = [
  1110. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, zMin)},
  1111. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, zMin)},
  1112. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, zMin)},
  1113. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, zMin)}
  1114. ];
  1115. // calculate screen location of the points
  1116. top.forEach(function (obj) {
  1117. obj.screen = me._convert3Dto2D(obj.point);
  1118. });
  1119. bottom.forEach(function (obj) {
  1120. obj.screen = me._convert3Dto2D(obj.point);
  1121. });
  1122. // create five sides, calculate both corner points and center points
  1123. var surfaces = [
  1124. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  1125. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  1126. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  1127. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  1128. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  1129. ];
  1130. point.surfaces = surfaces;
  1131. // calculate the distance of each of the surface centers to the camera
  1132. for (let j = 0; j < surfaces.length; j++) {
  1133. surface = surfaces[j];
  1134. var transCenter = this._convertPointToTranslation(surface.center);
  1135. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  1136. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  1137. // but the current solution is fast/simple and works in 99.9% of all cases
  1138. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  1139. }
  1140. // order the surfaces by their (translated) depth
  1141. surfaces.sort(function (a, b) {
  1142. var diff = b.dist - a.dist;
  1143. if (diff) return diff;
  1144. // if equal depth, sort the top surface last
  1145. if (a.corners === top) return 1;
  1146. if (b.corners === top) return -1;
  1147. // both are equal
  1148. return 0;
  1149. });
  1150. // draw the ordered surfaces
  1151. ctx.lineWidth = this._getStrokeWidth(point);
  1152. ctx.strokeStyle = borderColor;
  1153. ctx.fillStyle = color;
  1154. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  1155. for (let j = 2; j < surfaces.length; j++) {
  1156. surface = surfaces[j];
  1157. this._polygon(ctx, surface.corners);
  1158. }
  1159. };
  1160. /**
  1161. * Draw a polygon using the passed points and fill it with the passed style and stroke.
  1162. *
  1163. * @param points an array of points.
  1164. * @param fillStyle optional; the fill style to set
  1165. * @param strokeStyle optional; the stroke style to set
  1166. */
  1167. Graph3d.prototype._polygon = function(ctx, points, fillStyle, strokeStyle) {
  1168. if (points.length < 2) {
  1169. return;
  1170. }
  1171. if (fillStyle !== undefined) {
  1172. ctx.fillStyle = fillStyle;
  1173. }
  1174. if (strokeStyle !== undefined) {
  1175. ctx.strokeStyle = strokeStyle;
  1176. }
  1177. ctx.beginPath();
  1178. ctx.moveTo(points[0].screen.x, points[0].screen.y);
  1179. for (var i = 1; i < points.length; ++i) {
  1180. var point = points[i];
  1181. ctx.lineTo(point.screen.x, point.screen.y);
  1182. }
  1183. ctx.closePath();
  1184. ctx.fill();
  1185. ctx.stroke(); // TODO: only draw stroke when strokeWidth > 0
  1186. };
  1187. /**
  1188. * @param size optional; if not specified use value from 'this._dotSize()`
  1189. */
  1190. Graph3d.prototype._drawCircle = function(ctx, point, color, borderColor, size) {
  1191. var radius = this._calcRadius(point, size);
  1192. ctx.lineWidth = this._getStrokeWidth(point);
  1193. ctx.strokeStyle = borderColor;
  1194. ctx.fillStyle = color;
  1195. ctx.beginPath();
  1196. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  1197. ctx.fill();
  1198. ctx.stroke();
  1199. };
  1200. /**
  1201. * Determine the colors for the 'regular' graph styles.
  1202. */
  1203. Graph3d.prototype._getColorsRegular = function(point) {
  1204. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1205. var hue = (1 - (point.point.z - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  1206. var color = this._hsv2rgb(hue, 1, 1);
  1207. var borderColor = this._hsv2rgb(hue, 1, 0.8);
  1208. return {
  1209. fill : color,
  1210. border: borderColor
  1211. };
  1212. };
  1213. /**
  1214. * Get the colors for the 'color' graph styles.
  1215. * These styles are currently: 'bar-color' and 'dot-color'
  1216. * Color may be set as a string representation of HTML color, like #ff00ff,
  1217. * or calculated from a number, for example, distance from this point
  1218. * The first option is useful when we have some pre-given legend, to which we have to adjust ourselves
  1219. * The second option is useful when we are interested in automatically setting the color, from some value,
  1220. * using some color scale
  1221. */
  1222. Graph3d.prototype._getColorsColor = function(point) {
  1223. // calculate the color based on the value
  1224. var color, borderColor;
  1225. if (typeof point.point.value === "string") {
  1226. color = point.point.value;
  1227. borderColor = point.point.value;
  1228. }
  1229. else {
  1230. var hue = (1 - (point.point.value - this.valueRange.min) * this.scale.value) * 240;
  1231. color = this._hsv2rgb(hue, 1, 1);
  1232. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1233. }
  1234. return {
  1235. fill : color,
  1236. border : borderColor
  1237. };
  1238. };
  1239. /**
  1240. * Get the colors for the 'size' graph styles.
  1241. * These styles are currently: 'bar-size' and 'dot-size'
  1242. */
  1243. Graph3d.prototype._getColorsSize = function() {
  1244. return {
  1245. fill : this.dataColor.fill,
  1246. border : this.dataColor.stroke
  1247. };
  1248. };
  1249. /**
  1250. * Determine the size of a point on-screen, as determined by the
  1251. * distance to the camera.
  1252. *
  1253. * @param size the size that needs to be translated to screen coordinates.
  1254. * optional; if not passed, use the default point size.
  1255. */
  1256. Graph3d.prototype._calcRadius = function(point, size) {
  1257. if (size === undefined) {
  1258. size = this._dotSize();
  1259. }
  1260. var radius;
  1261. if (this.showPerspective) {
  1262. radius = size / -point.trans.z;
  1263. }
  1264. else {
  1265. radius = size * -(this.eye.z / this.camera.getArmLength());
  1266. }
  1267. if (radius < 0) {
  1268. radius = 0;
  1269. }
  1270. return radius;
  1271. };
  1272. // -----------------------------------------------------------------------------
  1273. // Methods for drawing points per graph style.
  1274. // -----------------------------------------------------------------------------
  1275. /**
  1276. * Draw single datapoint for graph style 'bar'.
  1277. */
  1278. Graph3d.prototype._redrawBarGraphPoint = function(ctx, point) {
  1279. var xWidth = this.xBarWidth / 2;
  1280. var yWidth = this.yBarWidth / 2;
  1281. var colors = this._getColorsRegular(point);
  1282. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  1283. };
  1284. /**
  1285. * Draw single datapoint for graph style 'bar-color'.
  1286. */
  1287. Graph3d.prototype._redrawBarColorGraphPoint = function(ctx, point) {
  1288. var xWidth = this.xBarWidth / 2;
  1289. var yWidth = this.yBarWidth / 2;
  1290. var colors = this._getColorsColor(point);
  1291. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  1292. };
  1293. /**
  1294. * Draw single datapoint for graph style 'bar-size'.
  1295. */
  1296. Graph3d.prototype._redrawBarSizeGraphPoint = function(ctx, point) {
  1297. // calculate size for the bar
  1298. var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
  1299. var xWidth = (this.xBarWidth / 2) * (fraction * 0.8 + 0.2);
  1300. var yWidth = (this.yBarWidth / 2) * (fraction * 0.8 + 0.2);
  1301. var colors = this._getColorsSize();
  1302. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  1303. };
  1304. /**
  1305. * Draw single datapoint for graph style 'dot'.
  1306. */
  1307. Graph3d.prototype._redrawDotGraphPoint = function(ctx, point) {
  1308. var colors = this._getColorsRegular(point);
  1309. this._drawCircle(ctx, point, colors.fill, colors.border);
  1310. };
  1311. /**
  1312. * Draw single datapoint for graph style 'dot-line'.
  1313. */
  1314. Graph3d.prototype._redrawDotLineGraphPoint = function(ctx, point) {
  1315. // draw a vertical line from the XY-plane to the graph value
  1316. var from = this._convert3Dto2D(point.bottom);
  1317. ctx.lineWidth = 1;
  1318. this._line(ctx, from, point.screen, this.gridColor);
  1319. this._redrawDotGraphPoint(ctx, point);
  1320. };
  1321. /**
  1322. * Draw single datapoint for graph style 'dot-color'.
  1323. */
  1324. Graph3d.prototype._redrawDotColorGraphPoint = function(ctx, point) {
  1325. var colors = this._getColorsColor(point);
  1326. this._drawCircle(ctx, point, colors.fill, colors.border);
  1327. };
  1328. /**
  1329. * Draw single datapoint for graph style 'dot-size'.
  1330. */
  1331. Graph3d.prototype._redrawDotSizeGraphPoint = function(ctx, point) {
  1332. var dotSize = this._dotSize();
  1333. var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
  1334. var sizeMin = dotSize*this.dotSizeMinFraction;
  1335. var sizeRange = dotSize*this.dotSizeMaxFraction - sizeMin;
  1336. var size = sizeMin + sizeRange*fraction;
  1337. var colors = this._getColorsSize();
  1338. this._drawCircle(ctx, point, colors.fill, colors.border, size);
  1339. };
  1340. /**
  1341. * Draw single datapoint for graph style 'surface'.
  1342. */
  1343. Graph3d.prototype._redrawSurfaceGraphPoint = function(ctx, point) {
  1344. var right = point.pointRight;
  1345. var top = point.pointTop;
  1346. var cross = point.pointCross;
  1347. if (point === undefined || right === undefined || top === undefined || cross === undefined) {
  1348. return;
  1349. }
  1350. var topSideVisible = true;
  1351. var fillStyle;
  1352. var strokeStyle;
  1353. if (this.showGrayBottom || this.showShadow) {
  1354. // calculate the cross product of the two vectors from center
  1355. // to left and right, in order to know whether we are looking at the
  1356. // bottom or at the top side. We can also use the cross product
  1357. // for calculating light intensity
  1358. var aDiff = Point3d.subtract(cross.trans, point.trans);
  1359. var bDiff = Point3d.subtract(top.trans, right.trans);
  1360. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  1361. var len = crossproduct.length();
  1362. // FIXME: there is a bug with determining the surface side (shadow or colored)
  1363. topSideVisible = (crossproduct.z > 0);
  1364. }
  1365. if (topSideVisible) {
  1366. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1367. var zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  1368. var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  1369. var s = 1; // saturation
  1370. var v;
  1371. if (this.showShadow) {
  1372. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  1373. fillStyle = this._hsv2rgb(h, s, v);
  1374. strokeStyle = fillStyle;
  1375. }
  1376. else {
  1377. v = 1;
  1378. fillStyle = this._hsv2rgb(h, s, v);
  1379. strokeStyle = this.axisColor; // TODO: should be customizable
  1380. }
  1381. }
  1382. else {
  1383. fillStyle = 'gray';
  1384. strokeStyle = this.axisColor;
  1385. }
  1386. ctx.lineWidth = this._getStrokeWidth(point);
  1387. // TODO: only draw stroke when strokeWidth > 0
  1388. var points = [point, right, cross, top];
  1389. this._polygon(ctx, points, fillStyle, strokeStyle);
  1390. };
  1391. /**
  1392. * Helper method for _redrawGridGraphPoint()
  1393. */
  1394. Graph3d.prototype._drawGridLine = function(ctx, from, to) {
  1395. if (from === undefined || to === undefined) {
  1396. return;
  1397. }
  1398. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1399. var zAvg = (from.point.z + to.point.z) / 2;
  1400. var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  1401. ctx.lineWidth = this._getStrokeWidth(from) * 2;
  1402. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  1403. this._line(ctx, from.screen, to.screen);
  1404. };
  1405. /**
  1406. * Draw single datapoint for graph style 'Grid'.
  1407. */
  1408. Graph3d.prototype._redrawGridGraphPoint = function(ctx, point) {
  1409. this._drawGridLine(ctx, point, point.pointRight);
  1410. this._drawGridLine(ctx, point, point.pointTop);
  1411. };
  1412. /**
  1413. * Draw single datapoint for graph style 'line'.
  1414. */
  1415. Graph3d.prototype._redrawLineGraphPoint = function(ctx, point) {
  1416. if (point.pointNext === undefined) {
  1417. return;
  1418. }
  1419. ctx.lineWidth = this._getStrokeWidth(point);
  1420. ctx.strokeStyle = this.dataColor.stroke;
  1421. this._line(ctx, point.screen, point.pointNext.screen);
  1422. };
  1423. /**
  1424. * Draw all datapoints for currently selected graph style.
  1425. *
  1426. */
  1427. Graph3d.prototype._redrawDataGraph = function() {
  1428. var ctx = this._getContext();
  1429. var i;
  1430. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1431. return; // TODO: throw exception?
  1432. this._calcTranslations(this.dataPoints);
  1433. for (i = 0; i < this.dataPoints.length; i++) {
  1434. var point = this.dataPoints[i];
  1435. // Using call() ensures that the correct context is used
  1436. this._pointDrawingMethod.call(this, ctx, point);
  1437. }
  1438. };
  1439. // -----------------------------------------------------------------------------
  1440. // End methods for drawing points per graph style.
  1441. // -----------------------------------------------------------------------------
  1442. /**
  1443. * Store startX, startY and startOffset for mouse operations
  1444. *
  1445. * @param {Event} event The event that occurred
  1446. */
  1447. Graph3d.prototype._storeMousePosition = function(event) {
  1448. // get mouse position (different code for IE and all other browsers)
  1449. this.startMouseX = getMouseX(event);
  1450. this.startMouseY = getMouseY(event);
  1451. this._startCameraOffset = this.camera.getOffset();
  1452. };
  1453. /**
  1454. * Start a moving operation inside the provided parent element
  1455. * @param {Event} event The event that occurred (required for
  1456. * retrieving the mouse position)
  1457. */
  1458. Graph3d.prototype._onMouseDown = function(event) {
  1459. event = event || window.event;
  1460. // check if mouse is still down (may be up when focus is lost for example
  1461. // in an iframe)
  1462. if (this.leftButtonDown) {
  1463. this._onMouseUp(event);
  1464. }
  1465. // only react on left mouse button down
  1466. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  1467. if (!this.leftButtonDown && !this.touchDown) return;
  1468. this._storeMousePosition(event);
  1469. this.startStart = new Date(this.start);
  1470. this.startEnd = new Date(this.end);
  1471. this.startArmRotation = this.camera.getArmRotation();
  1472. this.frame.style.cursor = 'move';
  1473. // add event listeners to handle moving the contents
  1474. // we store the function onmousemove and onmouseup in the graph, so we can
  1475. // remove the eventlisteners lateron in the function mouseUp()
  1476. var me = this;
  1477. this.onmousemove = function (event) {me._onMouseMove(event);};
  1478. this.onmouseup = function (event) {me._onMouseUp(event);};
  1479. util.addEventListener(document, 'mousemove', me.onmousemove);
  1480. util.addEventListener(document, 'mouseup', me.onmouseup);
  1481. util.preventDefault(event);
  1482. };
  1483. /**
  1484. * Perform moving operating.
  1485. * This function activated from within the funcion Graph.mouseDown().
  1486. * @param {Event} event Well, eehh, the event
  1487. */
  1488. Graph3d.prototype._onMouseMove = function (event) {
  1489. this.moving = true;
  1490. event = event || window.event;
  1491. // calculate change in mouse position
  1492. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  1493. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  1494. // move with ctrl or rotate by other
  1495. if (event && event.ctrlKey === true) {
  1496. // calculate change in mouse position
  1497. var scaleX = this.frame.clientWidth * 0.5;
  1498. var scaleY = this.frame.clientHeight * 0.5;
  1499. var offXNew = (this._startCameraOffset.x || 0) - ((diffX / scaleX) * this.camera.armLength) * 0.8;
  1500. var offYNew = (this._startCameraOffset.y || 0) + ((diffY / scaleY) * this.camera.armLength) * 0.8;
  1501. this.camera.setOffset(offXNew, offYNew);
  1502. this._storeMousePosition(event);
  1503. } else {
  1504. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  1505. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  1506. var snapAngle = 4; // degrees
  1507. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  1508. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  1509. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  1510. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  1511. horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001;
  1512. }
  1513. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  1514. horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001;
  1515. }
  1516. // snap vertically to nice angles
  1517. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  1518. verticalNew = Math.round(verticalNew / Math.PI) * Math.PI;
  1519. }
  1520. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  1521. verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI;
  1522. }
  1523. this.camera.setArmRotation(horizontalNew, verticalNew);
  1524. }
  1525. this.redraw();
  1526. // fire a cameraPositionChange event
  1527. var parameters = this.getCameraPosition();
  1528. this.emit('cameraPositionChange', parameters);
  1529. util.preventDefault(event);
  1530. };
  1531. /**
  1532. * Stop moving operating.
  1533. * This function activated from within the funcion Graph.mouseDown().
  1534. * @param {event} event The event
  1535. */
  1536. Graph3d.prototype._onMouseUp = function (event) {
  1537. this.frame.style.cursor = 'auto';
  1538. this.leftButtonDown = false;
  1539. // remove event listeners here
  1540. util.removeEventListener(document, 'mousemove', this.onmousemove);
  1541. util.removeEventListener(document, 'mouseup', this.onmouseup);
  1542. util.preventDefault(event);
  1543. };
  1544. /**
  1545. * @param {event} event The event
  1546. */
  1547. Graph3d.prototype._onClick = function (event) {
  1548. if (!this.onclick_callback)
  1549. return;
  1550. if (!this.moving) {
  1551. var boundingRect = this.frame.getBoundingClientRect();
  1552. var mouseX = getMouseX(event) - boundingRect.left;
  1553. var mouseY = getMouseY(event) - boundingRect.top;
  1554. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  1555. if (dataPoint)
  1556. this.onclick_callback(dataPoint.point.data);
  1557. }
  1558. else { // disable onclick callback, if it came immediately after rotate/pan
  1559. this.moving = false;
  1560. }
  1561. util.preventDefault(event);
  1562. };
  1563. /**
  1564. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  1565. * @param {Event} event A mouse move event
  1566. */
  1567. Graph3d.prototype._onTooltip = function (event) {
  1568. var delay = 300; // ms
  1569. var boundingRect = this.frame.getBoundingClientRect();
  1570. var mouseX = getMouseX(event) - boundingRect.left;
  1571. var mouseY = getMouseY(event) - boundingRect.top;
  1572. if (!this.showTooltip) {
  1573. return;
  1574. }
  1575. if (this.tooltipTimeout) {
  1576. clearTimeout(this.tooltipTimeout);
  1577. }
  1578. // (delayed) display of a tooltip only if no mouse button is down
  1579. if (this.leftButtonDown) {
  1580. this._hideTooltip();
  1581. return;
  1582. }
  1583. if (this.tooltip && this.tooltip.dataPoint) {
  1584. // tooltip is currently visible
  1585. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  1586. if (dataPoint !== this.tooltip.dataPoint) {
  1587. // datapoint changed
  1588. if (dataPoint) {
  1589. this._showTooltip(dataPoint);
  1590. }
  1591. else {
  1592. this._hideTooltip();
  1593. }
  1594. }
  1595. }
  1596. else {
  1597. // tooltip is currently not visible
  1598. var me = this;
  1599. this.tooltipTimeout = setTimeout(function () {
  1600. me.tooltipTimeout = null;
  1601. // show a tooltip if we have a data point
  1602. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  1603. if (dataPoint) {
  1604. me._showTooltip(dataPoint);
  1605. }
  1606. }, delay);
  1607. }
  1608. };
  1609. /**
  1610. * Event handler for touchstart event on mobile devices
  1611. */
  1612. Graph3d.prototype._onTouchStart = function(event) {
  1613. this.touchDown = true;
  1614. var me = this;
  1615. this.ontouchmove = function (event) {me._onTouchMove(event);};
  1616. this.ontouchend = function (event) {me._onTouchEnd(event);};
  1617. util.addEventListener(document, 'touchmove', me.ontouchmove);
  1618. util.addEventListener(document, 'touchend', me.ontouchend);
  1619. this._onMouseDown(event);
  1620. };
  1621. /**
  1622. * Event handler for touchmove event on mobile devices
  1623. */
  1624. Graph3d.prototype._onTouchMove = function(event) {
  1625. this._onMouseMove(event);
  1626. };
  1627. /**
  1628. * Event handler for touchend event on mobile devices
  1629. */
  1630. Graph3d.prototype._onTouchEnd = function(event) {
  1631. this.touchDown = false;
  1632. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  1633. util.removeEventListener(document, 'touchend', this.ontouchend);
  1634. this._onMouseUp(event);
  1635. };
  1636. /**
  1637. * Event handler for mouse wheel event, used to zoom the graph
  1638. * Code from http://adomas.org/javascript-mouse-wheel/
  1639. * @param {event} event The event
  1640. */
  1641. Graph3d.prototype._onWheel = function(event) {
  1642. if (!event) /* For IE. */
  1643. event = window.event;
  1644. // retrieve delta
  1645. var delta = 0;
  1646. if (event.wheelDelta) { /* IE/Opera. */
  1647. delta = event.wheelDelta/120;
  1648. } else if (event.detail) { /* Mozilla case. */
  1649. // In Mozilla, sign of delta is different than in IE.
  1650. // Also, delta is multiple of 3.
  1651. delta = -event.detail/3;
  1652. }
  1653. // If delta is nonzero, handle it.
  1654. // Basically, delta is now positive if wheel was scrolled up,
  1655. // and negative, if wheel was scrolled down.
  1656. if (delta) {
  1657. var oldLength = this.camera.getArmLength();
  1658. var newLength = oldLength * (1 - delta / 10);
  1659. this.camera.setArmLength(newLength);
  1660. this.redraw();
  1661. this._hideTooltip();
  1662. }
  1663. // fire a cameraPositionChange event
  1664. var parameters = this.getCameraPosition();
  1665. this.emit('cameraPositionChange', parameters);
  1666. // Prevent default actions caused by mouse wheel.
  1667. // That might be ugly, but we handle scrolls somehow
  1668. // anyway, so don't bother here..
  1669. util.preventDefault(event);
  1670. };
  1671. /**
  1672. * Test whether a point lies inside given 2D triangle
  1673. *
  1674. * @param {Point2d} point
  1675. * @param {Point2d[]} triangle
  1676. * @returns {boolean} true if given point lies inside or on the edge of the
  1677. * triangle, false otherwise
  1678. * @private
  1679. */
  1680. Graph3d.prototype._insideTriangle = function (point, triangle) {
  1681. var a = triangle[0],
  1682. b = triangle[1],
  1683. c = triangle[2];
  1684. function sign (x) {
  1685. return x > 0 ? 1 : x < 0 ? -1 : 0;
  1686. }
  1687. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  1688. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  1689. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  1690. // each of the three signs must be either equal to each other or zero
  1691. return (as == 0 || bs == 0 || as == bs) &&
  1692. (bs == 0 || cs == 0 || bs == cs) &&
  1693. (as == 0 || cs == 0 || as == cs);
  1694. };
  1695. /**
  1696. * Find a data point close to given screen position (x, y)
  1697. *
  1698. * @param {Number} x
  1699. * @param {Number} y
  1700. * @returns {Object | null} The closest data point or null if not close to any
  1701. * data point
  1702. * @private
  1703. */
  1704. Graph3d.prototype._dataPointFromXY = function (x, y) {
  1705. var i,
  1706. distMax = 100, // px
  1707. dataPoint = null,
  1708. closestDataPoint = null,
  1709. closestDist = null,
  1710. center = new Point2d(x, y);
  1711. if (this.style === Graph3d.STYLE.BAR ||
  1712. this.style === Graph3d.STYLE.BARCOLOR ||
  1713. this.style === Graph3d.STYLE.BARSIZE) {
  1714. // the data points are ordered from far away to closest
  1715. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  1716. dataPoint = this.dataPoints[i];
  1717. var surfaces = dataPoint.surfaces;
  1718. if (surfaces) {
  1719. for (var s = surfaces.length - 1; s >= 0; s--) {
  1720. // split each surface in two triangles, and see if the center point is inside one of these
  1721. var surface = surfaces[s];
  1722. var corners = surface.corners;
  1723. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  1724. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  1725. if (this._insideTriangle(center, triangle1) ||
  1726. this._insideTriangle(center, triangle2)) {
  1727. // return immediately at the first hit
  1728. return dataPoint;
  1729. }
  1730. }
  1731. }
  1732. }
  1733. }
  1734. else {
  1735. // find the closest data point, using distance to the center of the point on 2d screen
  1736. for (i = 0; i < this.dataPoints.length; i++) {
  1737. dataPoint = this.dataPoints[i];
  1738. var point = dataPoint.screen;
  1739. if (point) {
  1740. var distX = Math.abs(x - point.x);
  1741. var distY = Math.abs(y - point.y);
  1742. var dist = Math.sqrt(distX * distX + distY * distY);
  1743. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  1744. closestDist = dist;
  1745. closestDataPoint = dataPoint;
  1746. }
  1747. }
  1748. }
  1749. }
  1750. return closestDataPoint;
  1751. };
  1752. /**
  1753. * Determine if the given style has bars
  1754. *
  1755. * @param {number} style the style to check
  1756. * @returns {boolean} true if bar style, false otherwise
  1757. */
  1758. Graph3d.prototype.hasBars = function(style) {
  1759. return style == Graph3d.STYLE.BAR ||
  1760. style == Graph3d.STYLE.BARCOLOR ||
  1761. style == Graph3d.STYLE.BARSIZE;
  1762. };
  1763. /**
  1764. * Display a tooltip for given data point
  1765. * @param {Object} dataPoint
  1766. * @private
  1767. */
  1768. Graph3d.prototype._showTooltip = function (dataPoint) {
  1769. var content, line, dot;
  1770. if (!this.tooltip) {
  1771. content = document.createElement('div');
  1772. Object.assign(content.style, {}, this.tooltipStyle.content);
  1773. content.style.position = 'absolute';
  1774. line = document.createElement('div');
  1775. Object.assign(line.style, {}, this.tooltipStyle.line);
  1776. line.style.position = 'absolute';
  1777. dot = document.createElement('div');
  1778. Object.assign(dot.style, {}, this.tooltipStyle.dot);
  1779. dot.style.position = 'absolute';
  1780. this.tooltip = {
  1781. dataPoint: null,
  1782. dom: {
  1783. content: content,
  1784. line: line,
  1785. dot: dot
  1786. }
  1787. };
  1788. }
  1789. else {
  1790. content = this.tooltip.dom.content;
  1791. line = this.tooltip.dom.line;
  1792. dot = this.tooltip.dom.dot;
  1793. }
  1794. this._hideTooltip();
  1795. this.tooltip.dataPoint = dataPoint;
  1796. if (typeof this.showTooltip === 'function') {
  1797. content.innerHTML = this.showTooltip(dataPoint.point);
  1798. }
  1799. else {
  1800. content.innerHTML = '<table>' +
  1801. '<tr><td>' + this.xLabel + ':</td><td>' + dataPoint.point.x + '</td></tr>' +
  1802. '<tr><td>' + this.yLabel + ':</td><td>' + dataPoint.point.y + '</td></tr>' +
  1803. '<tr><td>' + this.zLabel + ':</td><td>' + dataPoint.point.z + '</td></tr>' +
  1804. '</table>';
  1805. }
  1806. content.style.left = '0';
  1807. content.style.top = '0';
  1808. this.frame.appendChild(content);
  1809. this.frame.appendChild(line);
  1810. this.frame.appendChild(dot);
  1811. // calculate sizes
  1812. var contentWidth = content.offsetWidth;
  1813. var contentHeight = content.offsetHeight;
  1814. var lineHeight = line.offsetHeight;
  1815. var dotWidth = dot.offsetWidth;
  1816. var dotHeight = dot.offsetHeight;
  1817. var left = dataPoint.screen.x - contentWidth / 2;
  1818. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  1819. line.style.left = dataPoint.screen.x + 'px';
  1820. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  1821. content.style.left = left + 'px';
  1822. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  1823. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  1824. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  1825. };
  1826. /**
  1827. * Hide the tooltip when displayed
  1828. * @private
  1829. */
  1830. Graph3d.prototype._hideTooltip = function () {
  1831. if (this.tooltip) {
  1832. this.tooltip.dataPoint = null;
  1833. for (var prop in this.tooltip.dom) {
  1834. if (this.tooltip.dom.hasOwnProperty(prop)) {
  1835. var elem = this.tooltip.dom[prop];
  1836. if (elem && elem.parentNode) {
  1837. elem.parentNode.removeChild(elem);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. };
  1843. /**--------------------------------------------------------------------------**/
  1844. /**
  1845. * Get the horizontal mouse position from a mouse event
  1846. *
  1847. * @param {Event} event
  1848. * @returns {Number} mouse x
  1849. */
  1850. function getMouseX (event) {
  1851. if ('clientX' in event) return event.clientX;
  1852. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  1853. }
  1854. /**
  1855. * Get the vertical mouse position from a mouse event
  1856. *
  1857. * @param {Event} event
  1858. * @returns {Number} mouse y
  1859. */
  1860. function getMouseY (event) {
  1861. if ('clientY' in event) return event.clientY;
  1862. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  1863. }
  1864. // -----------------------------------------------------------------------------
  1865. // Public methods for specific settings
  1866. // -----------------------------------------------------------------------------
  1867. /**
  1868. * Set the rotation and distance of the camera
  1869. *
  1870. * @param {Object} pos An object with the camera position
  1871. * @param {?Number} pos.horizontal The horizontal rotation, between 0 and 2*PI.
  1872. * Optional, can be left undefined.
  1873. * @param {?Number} pos.vertical The vertical rotation, between 0 and 0.5*PI.
  1874. * if vertical=0.5*PI, the graph is shown from
  1875. * the top. Optional, can be left undefined.
  1876. * @param {?Number} pos.distance The (normalized) distance of the camera to the
  1877. * center of the graph, a value between 0.71 and
  1878. * 5.0. Optional, can be left undefined.
  1879. */
  1880. Graph3d.prototype.setCameraPosition = function(pos) {
  1881. Settings.setCameraPosition(pos, this);
  1882. this.redraw();
  1883. };
  1884. /**
  1885. * Set a new size for the graph
  1886. *
  1887. * @param {string} width Width in pixels or percentage (for example '800px'
  1888. * or '50%')
  1889. * @param {string} height Height in pixels or percentage (for example '400px'
  1890. * or '30%')
  1891. */
  1892. Graph3d.prototype.setSize = function(width, height) {
  1893. this._setSize(width, height);
  1894. this.redraw();
  1895. };
  1896. // -----------------------------------------------------------------------------
  1897. // End public methods for specific settings
  1898. // -----------------------------------------------------------------------------
  1899. module.exports = Graph3d;