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.

693 lines
20 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. import PhysicsBase from './PhysicsBase';
  2. import PhysicsWorker from 'worker!./PhysicsWorkerWrapper';
  3. var util = require('../../util');
  4. class PhysicsEngine extends PhysicsBase {
  5. constructor(body) {
  6. super();
  7. this.body = body;
  8. this.physicsEnabled = true;
  9. this.simulationInterval = 1000 / 60;
  10. this.requiresTimeout = true;
  11. this.freezeCache = {};
  12. this.renderTimer = undefined;
  13. this.ready = false; // will be set to true if the stabilize
  14. // default options
  15. this.defaultOptions = {
  16. enabled: true,
  17. useWorker: false,
  18. barnesHut: {
  19. theta: 0.5,
  20. gravitationalConstant: -2000,
  21. centralGravity: 0.3,
  22. springLength: 95,
  23. springConstant: 0.04,
  24. damping: 0.09,
  25. avoidOverlap: 0
  26. },
  27. forceAtlas2Based: {
  28. theta: 0.5,
  29. gravitationalConstant: -50,
  30. centralGravity: 0.01,
  31. springConstant: 0.08,
  32. springLength: 100,
  33. damping: 0.4,
  34. avoidOverlap: 0
  35. },
  36. repulsion: {
  37. centralGravity: 0.2,
  38. springLength: 200,
  39. springConstant: 0.05,
  40. nodeDistance: 100,
  41. damping: 0.09,
  42. avoidOverlap: 0
  43. },
  44. hierarchicalRepulsion: {
  45. centralGravity: 0.0,
  46. springLength: 100,
  47. springConstant: 0.01,
  48. nodeDistance: 120,
  49. damping: 0.09
  50. },
  51. maxVelocity: 50,
  52. minVelocity: 0.75, // px/s
  53. solver: 'barnesHut',
  54. stabilization: {
  55. enabled: true,
  56. iterations: 1000, // maximum number of iteration to stabilize
  57. updateInterval: 50,
  58. onlyDynamicEdges: false,
  59. fit: true
  60. },
  61. timestep: 0.5,
  62. adaptiveTimestep: true
  63. };
  64. util.extend(this.options, this.defaultOptions);
  65. this.layoutFailed = false;
  66. this.draggingNodes = [];
  67. this.positionUpdateHandler = () => {};
  68. this.physicsUpdateHandler = () => {};
  69. this.emit = this.body.emitter.emit;
  70. this.bindEventListeners();
  71. }
  72. bindEventListeners() {
  73. this.body.emitter.on('initPhysics', () => {this.initPhysics();});
  74. this.body.emitter.on('_layoutFailed', () => {this.layoutFailed = true;});
  75. this.body.emitter.on('resetPhysics', () => {this.stopSimulation(); this.ready = false;});
  76. this.body.emitter.on('disablePhysics', () => {this.physicsEnabled = false; this.stopSimulation();});
  77. this.body.emitter.on('restorePhysics', () => {
  78. this.setOptions(this.options);
  79. if (this.ready === true) {
  80. this.startSimulation();
  81. }
  82. });
  83. this.body.emitter.on('startSimulation', () => {
  84. if (this.ready === true) {
  85. this.startSimulation();
  86. }
  87. });
  88. this.body.emitter.on('stopSimulation', () => {this.stopSimulation();});
  89. this.body.emitter.on('destroy', () => {
  90. this.stopSimulation(false);
  91. this.body.emitter.off();
  92. });
  93. this.body.emitter.on('_positionUpdate', (properties) => this.positionUpdateHandler(properties));
  94. this.body.emitter.on('_physicsUpdate', (properties) => this.physicsUpdateHandler(properties));
  95. this.body.emitter.on('dragStart', (properties) => {
  96. this.draggingNodes = properties.nodes;
  97. });
  98. this.body.emitter.on('dragEnd', () => {
  99. this.draggingNodes = [];
  100. });
  101. this.body.emitter.on('destroy', () => {
  102. if (this.physicsWorker) {
  103. this.physicsWorker.terminate();
  104. this.physicsWorker = undefined;
  105. }
  106. });
  107. }
  108. /**
  109. * set the physics options
  110. * @param options
  111. */
  112. setOptions(options) {
  113. if (options !== undefined) {
  114. if (options === false) {
  115. this.options.enabled = false;
  116. this.physicsEnabled = false;
  117. this.stopSimulation();
  118. }
  119. else {
  120. this.physicsEnabled = true;
  121. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  122. util.mergeOptions(this.options, options, 'stabilization')
  123. if (options.enabled === undefined) {
  124. this.options.enabled = true;
  125. }
  126. if (this.options.enabled === false) {
  127. this.physicsEnabled = false;
  128. this.stopSimulation();
  129. }
  130. // set the timestep
  131. this.timestep = this.options.timestep;
  132. }
  133. }
  134. if (this.options.useWorker) {
  135. this.initPhysicsWorker();
  136. this.physicsWorker.postMessage({type: 'options', data: this.options});
  137. } else {
  138. this.initEmbeddedPhysics();
  139. }
  140. }
  141. /**
  142. * configure the engine.
  143. */
  144. initEmbeddedPhysics() {
  145. this.positionUpdateHandler = () => {};
  146. this.physicsUpdateHandler = (properties) => {
  147. if (properties.options.physics !== undefined) {
  148. // we've received a node that has changed physics state
  149. // so rebuild physicsBody
  150. this.initPhysicsData();
  151. }
  152. // else we're accessing the information directly out of the node
  153. // so no need to do anything.
  154. };
  155. if (this.physicsWorker) {
  156. this.options.useWorker = false;
  157. this.physicsWorker.terminate();
  158. this.physicsWorker = undefined;
  159. this.initPhysicsData();
  160. }
  161. this.initPhysicsSolvers();
  162. }
  163. initPhysicsWorker() {
  164. if (!this.physicsWorker) {
  165. // setup path to webworker javascript file
  166. if (!__webpack_public_path__) {
  167. // search for element with id of 'visjs'
  168. let parentScript = document.getElementById('visjs');
  169. if (parentScript) {
  170. let src = parentScript.getAttribute('src')
  171. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  172. } else {
  173. // search all scripts for 'vis.js'
  174. let scripts = document.getElementsByTagName('script');
  175. for (let i = 0; i < scripts.length; i++) {
  176. let src = scripts[i].getAttribute('src');
  177. if (src && src.length >= 6) {
  178. let position = src.length - 6;
  179. let index = src.indexOf('vis.js', position);
  180. if (index === position) {
  181. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  182. break;
  183. }
  184. }
  185. }
  186. }
  187. }
  188. // launch webworker
  189. this.physicsWorker = new PhysicsWorker();
  190. this.physicsWorker.addEventListener('message', (event) => {
  191. this.physicsWorkerMessageHandler(event);
  192. });
  193. this.physicsWorker.onerror = (event) => {
  194. console.error('Falling back to embedded physics engine', event);
  195. this.initEmbeddedPhysics();
  196. // throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  197. };
  198. this.positionUpdateHandler = (positions) => {
  199. this.physicsWorker.postMessage({type: 'updatePositions', data: positions});
  200. };
  201. this.physicsUpdateHandler = (properties) => {
  202. this._physicsUpdateHandler(properties);
  203. };
  204. }
  205. }
  206. _physicsUpdateHandler(properties) {
  207. if (properties.options.physics !== undefined) {
  208. if (properties.options.physics) {
  209. let data = {
  210. nodes: {},
  211. edges: {}
  212. };
  213. if (properties.type === 'node') {
  214. data.nodes[properties.id] = this.createPhysicsNode(properties.id);
  215. } else if (properties.type === 'edge') {
  216. data.edges[properties.id] = this.createPhysicsEdge(properties.id);
  217. } else {
  218. console.warn('invalid element type');
  219. }
  220. this.physicsWorker.postMessage({
  221. type: 'addElements',
  222. data: data
  223. });
  224. } else {
  225. let data = {
  226. nodeIds: [],
  227. edgeIds: []
  228. };
  229. if (properties.type === 'node') {
  230. data.nodeIds = [properties.id.toString()];
  231. } else if (properties.type === 'edge') {
  232. data.edgeIds = [properties.id.toString()];
  233. } else {
  234. console.warn('invalid element type');
  235. }
  236. this.physicsWorker.postMessage({type: 'removeElements', data: data});
  237. }
  238. } else {
  239. this.physicsWorker.postMessage({type: 'updateProperties', data: properties});
  240. }
  241. }
  242. physicsWorkerMessageHandler(event) {
  243. var msg = event.data;
  244. switch (msg.type) {
  245. case 'tickResults':
  246. this.stabilized = msg.data.stabilized;
  247. this.stabilizationIterations = msg.data.stabilizationIterations;
  248. this._receivedPositions(msg.data.positions);
  249. break;
  250. case 'finalizeStabilization':
  251. this._finalizeStabilization();
  252. break;
  253. case 'emit':
  254. this.emit(msg.data.event, msg.data.data);
  255. break;
  256. default:
  257. console.warn('unhandled physics worker message:', msg);
  258. }
  259. }
  260. _receivedPositions(positions) {
  261. for (let i = 0; i < this.draggingNodes.length; i++) {
  262. delete positions[this.draggingNodes[i]];
  263. }
  264. let nodeIds = Object.keys(positions);
  265. for (let i = 0; i < nodeIds.length; i++) {
  266. let nodeId = nodeIds[i];
  267. let node = this.body.nodes[nodeId];
  268. // handle case where we get a positions from an old physicsObject
  269. if (node) {
  270. node.setX(positions[nodeId].x);
  271. node.setY(positions[nodeId].y);
  272. }
  273. }
  274. }
  275. /**
  276. * initialize the engine
  277. */
  278. initPhysics() {
  279. if (this.physicsEnabled === true && this.options.enabled === true) {
  280. if (this.options.stabilization.enabled === true) {
  281. this.stabilize();
  282. }
  283. else {
  284. this.stabilized = false;
  285. this.ready = true;
  286. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  287. this.startSimulation();
  288. }
  289. }
  290. else {
  291. this.ready = true;
  292. this.body.emitter.emit('fit');
  293. }
  294. }
  295. /**
  296. * Start the simulation
  297. */
  298. startSimulation() {
  299. if (this.physicsEnabled === true && this.options.enabled === true) {
  300. this.stabilized = false;
  301. this._updateWorkerStabilized();
  302. // when visible, adaptivity is disabled.
  303. this.adaptiveTimestep = false;
  304. // this sets the width of all nodes initially which could be required for the avoidOverlap
  305. this.body.emitter.emit("_resizeNodes");
  306. if (this.viewFunction === undefined) {
  307. this.viewFunction = this.simulationStep.bind(this);
  308. this.body.emitter.on('initRedraw', this.viewFunction);
  309. this.body.emitter.emit('_startRendering');
  310. }
  311. }
  312. else {
  313. this.body.emitter.emit('_redraw');
  314. }
  315. }
  316. /**
  317. * Stop the simulation, force stabilization.
  318. */
  319. stopSimulation(emit = true) {
  320. this.stabilized = true;
  321. this._updateWorkerStabilized();
  322. if (emit === true) {
  323. this._emitStabilized();
  324. }
  325. if (this.viewFunction !== undefined) {
  326. this.body.emitter.off('initRedraw', this.viewFunction);
  327. this.viewFunction = undefined;
  328. if (emit === true) {
  329. this.body.emitter.emit('_stopRendering');
  330. }
  331. }
  332. }
  333. _updateWorkerStabilized() {
  334. if (this.physicsWorker) {
  335. this.physicsWorker.postMessage({
  336. type: 'setStabilized',
  337. data: this.stabilized
  338. });
  339. }
  340. }
  341. /**
  342. * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized.
  343. *
  344. */
  345. simulationStep() {
  346. if (this.physicsWorker) {
  347. this.physicsWorker.postMessage({type: 'physicsTick'});
  348. } else {
  349. // check if the physics have settled
  350. var startTime = Date.now();
  351. this.physicsTick();
  352. var physicsTime = Date.now() - startTime;
  353. // run double speed if it is a little graph
  354. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  355. this.physicsTick();
  356. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  357. this.runDoubleSpeed = true;
  358. }
  359. }
  360. if (this.stabilized === true) {
  361. this.stopSimulation();
  362. }
  363. }
  364. _sendWorkerStabilized() {
  365. if (this.physicsWorker) {
  366. this.physicsWorker.postMessage({
  367. type: 'stabilized'
  368. });
  369. }
  370. }
  371. /**
  372. * trigger the stabilized event.
  373. * @private
  374. */
  375. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  376. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  377. setTimeout(() => {
  378. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  379. this.startedStabilization = false;
  380. this.stabilizationIterations = 0;
  381. this._sendWorkerStabilized();
  382. }, 0);
  383. }
  384. }
  385. createPhysicsNode(nodeId) {
  386. let node = this.body.nodes[nodeId];
  387. if (node) {
  388. return {
  389. id: node.id.toString(),
  390. x: node.x,
  391. y: node.y,
  392. // TODO update on change
  393. edges: {
  394. length: node.edges.length
  395. },
  396. options: {
  397. fixed: {
  398. x: node.options.fixed.x,
  399. y: node.options.fixed.y
  400. },
  401. mass: node.options.mass
  402. }
  403. }
  404. }
  405. }
  406. createPhysicsEdge(edgeId) {
  407. let edge = this.body.edges[edgeId];
  408. if (edge && edge.options.physics === true) {
  409. let physicsEdge = {
  410. id: edge.id,
  411. connected: edge.connected,
  412. edgeType: {},
  413. toId: edge.toId,
  414. fromId: edge.fromId,
  415. options: {
  416. length: edge.length
  417. }
  418. };
  419. // TODO test/implment dynamic
  420. if (edge.edgeType.via) {
  421. physicsEdge.edgeType = {
  422. via: {
  423. id: edge.edgeType.via.id
  424. }
  425. }
  426. }
  427. return physicsEdge;
  428. }
  429. }
  430. /**
  431. * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time.
  432. *
  433. * @private
  434. */
  435. initPhysicsData() {
  436. let nodes = this.body.nodes;
  437. let edges = this.body.edges;
  438. this.physicsBody.forces = {};
  439. this.physicsBody.physicsNodeIndices = [];
  440. this.physicsBody.physicsEdgeIndices = [];
  441. let physicsWorkerNodes = {};
  442. let physicsWorkerEdges = {};
  443. // get node indices for physics
  444. for (let nodeId in nodes) {
  445. if (nodes.hasOwnProperty(nodeId)) {
  446. if (nodes[nodeId].options.physics === true) {
  447. this.physicsBody.physicsNodeIndices.push(nodeId);
  448. if (this.physicsWorker) {
  449. physicsWorkerNodes[nodeId] = this.createPhysicsNode(nodeId);
  450. }
  451. }
  452. }
  453. }
  454. // get edge indices for physics
  455. for (let edgeId in edges) {
  456. if (edges.hasOwnProperty(edgeId)) {
  457. if (edges[edgeId].options.physics === true) {
  458. this.physicsBody.physicsEdgeIndices.push(edgeId);
  459. if (this.physicsWorker) {
  460. physicsWorkerEdges[edgeId] = this.createPhysicsEdge(edgeId);
  461. }
  462. }
  463. }
  464. }
  465. // get the velocity and the forces vector
  466. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  467. let nodeId = this.physicsBody.physicsNodeIndices[i];
  468. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  469. // forces can be reset because they are recalculated. Velocities have to persist.
  470. if (this.physicsBody.velocities[nodeId] === undefined) {
  471. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  472. }
  473. }
  474. // clean deleted nodes from the velocity vector
  475. for (let nodeId in this.physicsBody.velocities) {
  476. if (nodes[nodeId] === undefined) {
  477. delete this.physicsBody.velocities[nodeId];
  478. }
  479. }
  480. if (this.physicsWorker) {
  481. this.physicsWorker.postMessage({
  482. type: 'initPhysicsData',
  483. data: {
  484. nodes: physicsWorkerNodes,
  485. edges: physicsWorkerEdges
  486. }
  487. });
  488. }
  489. }
  490. /**
  491. * Perform the actual step
  492. *
  493. * @param nodeId
  494. * @param maxVelocity
  495. * @returns {number}
  496. * @private
  497. */
  498. _performStep(nodeId,maxVelocity) {
  499. let node = this.body.nodes[nodeId];
  500. let timestep = this.timestep;
  501. let forces = this.physicsBody.forces;
  502. let velocities = this.physicsBody.velocities;
  503. // store the state so we can revert
  504. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  505. if (node.options.fixed.x === false) {
  506. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  507. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  508. velocities[nodeId].x += ax * timestep; // velocity
  509. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  510. node.setX(node.x + velocities[nodeId].x * timestep); // position
  511. }
  512. else {
  513. forces[nodeId].x = 0;
  514. velocities[nodeId].x = 0;
  515. }
  516. if (node.options.fixed.y === false) {
  517. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  518. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  519. velocities[nodeId].y += ay * timestep; // velocity
  520. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  521. node.setY(node.y + velocities[nodeId].y * timestep); // position
  522. }
  523. else {
  524. forces[nodeId].y = 0;
  525. velocities[nodeId].y = 0;
  526. }
  527. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  528. return totalVelocity;
  529. }
  530. // TODO probably want to move freeze/restore to PhysicsBase and do in worker if running
  531. /**
  532. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  533. * because only the supportnodes for the smoothCurves have to settle.
  534. *
  535. * @private
  536. */
  537. _freezeNodes() {
  538. var nodes = this.body.nodes;
  539. for (var id in nodes) {
  540. if (nodes.hasOwnProperty(id)) {
  541. if (nodes[id].x && nodes[id].y) {
  542. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  543. nodes[id].setFixed(true);
  544. }
  545. }
  546. }
  547. }
  548. /**
  549. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  550. *
  551. * @private
  552. */
  553. _restoreFrozenNodes() {
  554. var nodes = this.body.nodes;
  555. for (var id in nodes) {
  556. if (nodes.hasOwnProperty(id)) {
  557. if (this.freezeCache[id] !== undefined) {
  558. nodes[id].setFixed({x: this.freezeCache[id].x, y: this.freezeCache[id].y});
  559. }
  560. }
  561. }
  562. this.freezeCache = {};
  563. }
  564. /**
  565. * Find a stable position for all nodes
  566. * @private
  567. */
  568. stabilize(iterations = this.options.stabilization.iterations) {
  569. if (typeof iterations !== 'number') {
  570. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  571. iterations = this.options.stabilization.iterations;
  572. }
  573. if (this.physicsBody.physicsNodeIndices.length === 0) {
  574. this.ready = true;
  575. return;
  576. }
  577. // enable adaptive timesteps
  578. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  579. // this sets the width of all nodes initially which could be required for the avoidOverlap
  580. this.body.emitter.emit("_resizeNodes");
  581. // stop the render loop
  582. this.stopSimulation();
  583. // set stabilize to false
  584. this.stabilized = false;
  585. // block redraw requests
  586. this.body.emitter.emit('_blockRedraw');
  587. this.targetIterations = iterations;
  588. // start the stabilization
  589. if (this.options.stabilization.onlyDynamicEdges === true) {
  590. this._freezeNodes();
  591. }
  592. this.stabilizationIterations = 0;
  593. if (this.physicsWorker) {
  594. this.physicsWorker.postMessage({
  595. type: 'stabilize',
  596. data: {
  597. targetIterations: iterations
  598. }
  599. });
  600. } else {
  601. setTimeout(() => this._stabilizationBatch(), 0);
  602. }
  603. }
  604. /**
  605. * Wrap up the stabilization, fit and emit the events.
  606. * @private
  607. */
  608. _finalizeStabilization() {
  609. this.body.emitter.emit('_allowRedraw');
  610. if (this.options.stabilization.fit === true) {
  611. this.body.emitter.emit('fit');
  612. }
  613. if (this.options.stabilization.onlyDynamicEdges === true) {
  614. this._restoreFrozenNodes();
  615. }
  616. this.body.emitter.emit('stabilizationIterationsDone');
  617. this.body.emitter.emit('_requestRedraw');
  618. if (this.stabilized === true) {
  619. this._emitStabilized();
  620. }
  621. else {
  622. this.startSimulation();
  623. }
  624. this.ready = true;
  625. }
  626. }
  627. export default PhysicsEngine;