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.

2347 lines
71 KiB

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