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.

2530 lines
74 KiB

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