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.

684 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 'positions':
  246. this.stabilized = msg.data.stabilized;
  247. this._receivedPositions(msg.data.positions);
  248. break;
  249. case 'finalizeStabilization':
  250. this.stabilizationIterations = msg.data.stabilizationIterations;
  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. /**
  365. * trigger the stabilized event.
  366. * @private
  367. */
  368. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  369. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  370. setTimeout(() => {
  371. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  372. this.startedStabilization = false;
  373. this.stabilizationIterations = 0;
  374. }, 0);
  375. }
  376. }
  377. createPhysicsNode(nodeId) {
  378. let node = this.body.nodes[nodeId];
  379. if (node) {
  380. return {
  381. id: node.id.toString(),
  382. x: node.x,
  383. y: node.y,
  384. // TODO update on change
  385. edges: {
  386. length: node.edges.length
  387. },
  388. options: {
  389. fixed: {
  390. x: node.options.fixed.x,
  391. y: node.options.fixed.y
  392. },
  393. mass: node.options.mass
  394. }
  395. }
  396. }
  397. }
  398. createPhysicsEdge(edgeId) {
  399. let edge = this.body.edges[edgeId];
  400. if (edge && edge.options.physics === true) {
  401. let physicsEdge = {
  402. id: edge.id,
  403. connected: edge.connected,
  404. edgeType: {},
  405. toId: edge.toId,
  406. fromId: edge.fromId,
  407. options: {
  408. length: edge.length
  409. }
  410. };
  411. // TODO test/implment dynamic
  412. if (edge.edgeType.via) {
  413. physicsEdge.edgeType = {
  414. via: {
  415. id: edge.edgeType.via.id
  416. }
  417. }
  418. }
  419. return physicsEdge;
  420. }
  421. }
  422. /**
  423. * 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.
  424. *
  425. * @private
  426. */
  427. initPhysicsData() {
  428. let nodes = this.body.nodes;
  429. let edges = this.body.edges;
  430. this.physicsBody.forces = {};
  431. this.physicsBody.physicsNodeIndices = [];
  432. this.physicsBody.physicsEdgeIndices = [];
  433. let physicsWorkerNodes = {};
  434. let physicsWorkerEdges = {};
  435. // get node indices for physics
  436. for (let nodeId in nodes) {
  437. if (nodes.hasOwnProperty(nodeId)) {
  438. if (nodes[nodeId].options.physics === true) {
  439. this.physicsBody.physicsNodeIndices.push(nodeId);
  440. if (this.physicsWorker) {
  441. physicsWorkerNodes[nodeId] = this.createPhysicsNode(nodeId);
  442. }
  443. }
  444. }
  445. }
  446. // get edge indices for physics
  447. for (let edgeId in edges) {
  448. if (edges.hasOwnProperty(edgeId)) {
  449. if (edges[edgeId].options.physics === true) {
  450. this.physicsBody.physicsEdgeIndices.push(edgeId);
  451. if (this.physicsWorker) {
  452. physicsWorkerEdges[edgeId] = this.createPhysicsEdge(edgeId);
  453. }
  454. }
  455. }
  456. }
  457. // get the velocity and the forces vector
  458. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  459. let nodeId = this.physicsBody.physicsNodeIndices[i];
  460. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  461. // forces can be reset because they are recalculated. Velocities have to persist.
  462. if (this.physicsBody.velocities[nodeId] === undefined) {
  463. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  464. }
  465. }
  466. // clean deleted nodes from the velocity vector
  467. for (let nodeId in this.physicsBody.velocities) {
  468. if (nodes[nodeId] === undefined) {
  469. delete this.physicsBody.velocities[nodeId];
  470. }
  471. }
  472. if (this.physicsWorker) {
  473. this.physicsWorker.postMessage({
  474. type: 'initPhysicsData',
  475. data: {
  476. nodes: physicsWorkerNodes,
  477. edges: physicsWorkerEdges
  478. }
  479. });
  480. }
  481. }
  482. /**
  483. * Perform the actual step
  484. *
  485. * @param nodeId
  486. * @param maxVelocity
  487. * @returns {number}
  488. * @private
  489. */
  490. _performStep(nodeId,maxVelocity) {
  491. let node = this.body.nodes[nodeId];
  492. let timestep = this.timestep;
  493. let forces = this.physicsBody.forces;
  494. let velocities = this.physicsBody.velocities;
  495. // store the state so we can revert
  496. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  497. if (node.options.fixed.x === false) {
  498. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  499. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  500. velocities[nodeId].x += ax * timestep; // velocity
  501. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  502. node.setX(node.x + velocities[nodeId].x * timestep); // position
  503. }
  504. else {
  505. forces[nodeId].x = 0;
  506. velocities[nodeId].x = 0;
  507. }
  508. if (node.options.fixed.y === false) {
  509. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  510. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  511. velocities[nodeId].y += ay * timestep; // velocity
  512. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  513. node.setY(node.y + velocities[nodeId].y * timestep); // position
  514. }
  515. else {
  516. forces[nodeId].y = 0;
  517. velocities[nodeId].y = 0;
  518. }
  519. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  520. return totalVelocity;
  521. }
  522. // TODO probably want to move freeze/restore to PhysicsBase and do in worker if running
  523. /**
  524. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  525. * because only the supportnodes for the smoothCurves have to settle.
  526. *
  527. * @private
  528. */
  529. _freezeNodes() {
  530. var nodes = this.body.nodes;
  531. for (var id in nodes) {
  532. if (nodes.hasOwnProperty(id)) {
  533. if (nodes[id].x && nodes[id].y) {
  534. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  535. nodes[id].setFixed(true);
  536. }
  537. }
  538. }
  539. }
  540. /**
  541. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  542. *
  543. * @private
  544. */
  545. _restoreFrozenNodes() {
  546. var nodes = this.body.nodes;
  547. for (var id in nodes) {
  548. if (nodes.hasOwnProperty(id)) {
  549. if (this.freezeCache[id] !== undefined) {
  550. nodes[id].setFixed({x: this.freezeCache[id].x, y: this.freezeCache[id].y});
  551. }
  552. }
  553. }
  554. this.freezeCache = {};
  555. }
  556. /**
  557. * Find a stable position for all nodes
  558. * @private
  559. */
  560. stabilize(iterations = this.options.stabilization.iterations) {
  561. if (typeof iterations !== 'number') {
  562. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  563. iterations = this.options.stabilization.iterations;
  564. }
  565. if (this.physicsBody.physicsNodeIndices.length === 0) {
  566. this.ready = true;
  567. return;
  568. }
  569. // enable adaptive timesteps
  570. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  571. // this sets the width of all nodes initially which could be required for the avoidOverlap
  572. this.body.emitter.emit("_resizeNodes");
  573. // stop the render loop
  574. this.stopSimulation();
  575. // set stabilize to false
  576. this.stabilized = false;
  577. // block redraw requests
  578. this.body.emitter.emit('_blockRedraw');
  579. this.targetIterations = iterations;
  580. // start the stabilization
  581. if (this.options.stabilization.onlyDynamicEdges === true) {
  582. this._freezeNodes();
  583. }
  584. this.stabilizationIterations = 0;
  585. if (this.physicsWorker) {
  586. this.physicsWorker.postMessage({
  587. type: 'stabilize',
  588. data: {
  589. targetIterations: iterations
  590. }
  591. });
  592. } else {
  593. setTimeout(() => this._stabilizationBatch(), 0);
  594. }
  595. }
  596. /**
  597. * Wrap up the stabilization, fit and emit the events.
  598. * @private
  599. */
  600. _finalizeStabilization() {
  601. this.body.emitter.emit('_allowRedraw');
  602. if (this.options.stabilization.fit === true) {
  603. this.body.emitter.emit('fit');
  604. }
  605. if (this.options.stabilization.onlyDynamicEdges === true) {
  606. this._restoreFrozenNodes();
  607. }
  608. this.body.emitter.emit('stabilizationIterationsDone');
  609. this.body.emitter.emit('_requestRedraw');
  610. if (this.stabilized === true) {
  611. this._emitStabilized();
  612. }
  613. else {
  614. this.startSimulation();
  615. }
  616. this.ready = true;
  617. }
  618. }
  619. export default PhysicsEngine;