-
Notifications
You must be signed in to change notification settings - Fork 0
/
vivagraph.js
6881 lines (5742 loc) · 193 KB
/
vivagraph.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Viva=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* This is an entry point for global namespace. If you want to use separate
* modules individually - you are more than welcome to do so.
*/
var random = require('ngraph.random');
var Viva = {
lazyExtend: function() {
return require('ngraph.merge').apply(this, arguments);
},
randomIterator: function() {
return random.randomIterator.apply(random, arguments);
},
random: function() {
return random.random.apply(random, arguments);
},
events: require('ngraph.events')
};
Viva.Graph = {
version: require('./version.js'),
graph: require('ngraph.graph'),
serializer: function() {
return {
loadFromJSON: require('ngraph.fromjson'),
storeToJSON: require('ngraph.tojson')
};
},
centrality: require('./Algorithms/centrality.js'),
operations: require('./Algorithms/operations.js'),
geom: function() {
return {
intersect: require('gintersect'),
intersectRect: require('./Utils/intersectRect.js')
};
},
webgl: require('./WebGL/webgl.js'),
webglInputEvents: require('./WebGL/webglInputEvents.js'),
generator: function() {
return require('ngraph.generators');
},
Input: {
domInputManager: require('./Input/domInputManager.js'),
webglInputManager: require('./Input/webglInputManager.js')
},
Utils: {
// TODO: move to Input
dragndrop: require('./Input/dragndrop.js'),
findElementPosition: require('./Utils/findElementPosition.js'),
timer: require('./Utils/timer.js'),
getDimension: require('./Utils/getDimensions.js'),
events: require('./Utils/backwardCompatibleEvents.js')
},
Layout: {
forceDirected: require('ngraph.forcelayout'),
constant: require('./Layout/constant.js')
},
View: {
// TODO: Move `webglXXX` out to webgl namespace
Texture: require('./WebGL/texture.js'),
// TODO: This should not be even exported
webglAtlas: require('./WebGL/webglAtlas.js'),
webglImageNodeProgram: require('./WebGL/webglImageNodeProgram.js'),
webglLinkProgram: require('./WebGL/webglLinkProgram.js'),
webglNodeProgram: require('./WebGL/webglNodeProgram.js'),
webglLine: require('./WebGL/webglLine.js'),
webglSquare: require('./WebGL/webglSquare.js'),
webglImage: require('./WebGL/webglImage.js'),
webglGraphics: require('./View/webglGraphics.js'),
// TODO: Deprecate this:
_webglUtil: {
parseColor: require('./WebGL/parseColor.js')
},
// TODO: move to svg namespace
svgGraphics: require('./View/svgGraphics.js'),
renderer: require('./View/renderer.js'),
// deprecated
cssGraphics: function() {
throw new Error('cssGraphics is deprecated. Please use older version of vivagraph (< 0.7) if you need it');
},
svgNodeFactory: function() {
throw new Error('svgNodeFactory is deprecated. Please use older version of vivagraph (< 0.7) if you need it');
},
community: function() {
throw new Error('community is deprecated. Please use vivagraph < 0.7 if you need it, or `https://github.com/anvaka/ngraph.slpa` module');
}
},
Rect: require('./Utils/rect.js'),
svg: require('simplesvg'),
// TODO: should be camelCase
BrowserInfo: require('./Utils/browserInfo.js')
};
module.exports = Viva;
},{"./Algorithms/centrality.js":32,"./Algorithms/operations.js":33,"./Input/domInputManager.js":34,"./Input/dragndrop.js":35,"./Input/webglInputManager.js":36,"./Layout/constant.js":37,"./Utils/backwardCompatibleEvents.js":38,"./Utils/browserInfo.js":39,"./Utils/findElementPosition.js":41,"./Utils/getDimensions.js":42,"./Utils/intersectRect.js":43,"./Utils/rect.js":45,"./Utils/timer.js":46,"./View/renderer.js":48,"./View/svgGraphics.js":49,"./View/webglGraphics.js":50,"./WebGL/parseColor.js":51,"./WebGL/texture.js":52,"./WebGL/webgl.js":53,"./WebGL/webglAtlas.js":54,"./WebGL/webglImage.js":55,"./WebGL/webglImageNodeProgram.js":56,"./WebGL/webglInputEvents.js":57,"./WebGL/webglLine.js":58,"./WebGL/webglLinkProgram.js":59,"./WebGL/webglNodeProgram.js":60,"./WebGL/webglSquare.js":61,"./version.js":62,"gintersect":2,"ngraph.events":6,"ngraph.forcelayout":7,"ngraph.fromjson":21,"ngraph.generators":22,"ngraph.graph":23,"ngraph.merge":24,"ngraph.random":25,"ngraph.tojson":26,"simplesvg":27}],2:[function(require,module,exports){
module.exports = intersect;
/**
* Original authors: Mukesh Prasad, Appeared in Graphics Gem II book
* http://www.opensource.apple.com/source/graphviz/graphviz-498/graphviz/dynagraph/common/xlines.c
* and adopted to javascript version by Andrei Kashcha.
*
* This function computes whether two line segments,
* respectively joining the input points (x1,y1) -- (x2,y2)
* and the input points (x3,y3) -- (x4,y4) intersect.
* If the lines intersect, the output variables x, y are
* set to coordinates of the point of intersection.
*
* @param {Number} x1 First line segment coordinates
* @param {Number} y1 First line segment coordinates
* @param {Number} x2 First line segment coordinates
* @param {Number} x2 First line segment coordinates
*
* @param {Number} x3 Second line segment coordinates
* @param {Number} y3 Second line segment coordinates
* @param {Number} x4 Second line segment coordinates
* @param {Number} x4 Second line segment coordinates
*
* @return {Object} x, y coordinates of intersection point or falsy value if no
* intersection found..
*/
function intersect(
x1, y1, x2, y2, // first line segment
x3, y3, x4, y4 // second line segment
) {
var a1, a2, b1, b2, c1, c2, /* Coefficients of line eqns. */
r1, r2, r3, r4, /* 'Sign' values */
denom, offset, num, /* Intermediate values */
result = {
x: 0,
y: 0
};
/* Compute a1, b1, c1, where line joining points 1 and 2
* is "a1 x + b1 y + c1 = 0".
*/
a1 = y2 - y1;
b1 = x1 - x2;
c1 = x2 * y1 - x1 * y2;
/* Compute r3 and r4.
*/
r3 = a1 * x3 + b1 * y3 + c1;
r4 = a1 * x4 + b1 * y4 + c1;
/* Check signs of r3 and r4. If both point 3 and point 4 lie on
* same side of line 1, the line segments do not intersect.
*/
if (r3 !== 0 && r4 !== 0 && ((r3 >= 0) === (r4 >= 4))) {
return null; //no intersection.
}
/* Compute a2, b2, c2 */
a2 = y4 - y3;
b2 = x3 - x4;
c2 = x4 * y3 - x3 * y4;
/* Compute r1 and r2 */
r1 = a2 * x1 + b2 * y1 + c2;
r2 = a2 * x2 + b2 * y2 + c2;
/* Check signs of r1 and r2. If both point 1 and point 2 lie
* on same side of second line segment, the line segments do
* not intersect.
*/
if (r1 !== 0 && r2 !== 0 && ((r1 >= 0) === (r2 >= 0))) {
return null; // no intersection;
}
/* Line segments intersect: compute intersection point.
*/
denom = a1 * b2 - a2 * b1;
if (denom === 0) {
return null; // Actually collinear..
}
offset = denom < 0 ? -denom / 2 : denom / 2;
offset = 0.0;
/* The denom/2 is to get rounding instead of truncating. It
* is added or subtracted to the numerator, depending upon the
* sign of the numerator.
*/
num = b1 * c2 - b2 * c1;
result.x = (num < 0 ? num - offset : num + offset) / denom;
num = a2 * c1 - a1 * c2;
result.y = (num < 0 ? num - offset : num + offset) / denom;
return result;
}
},{}],3:[function(require,module,exports){
module.exports.degree = require('./src/degree.js');
module.exports.betweenness = require('./src/betweenness.js');
},{"./src/betweenness.js":4,"./src/degree.js":5}],4:[function(require,module,exports){
module.exports = betweennes;
/**
* I'm using http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
* as a reference for this implementation
*/
function betweennes(graph, oriented) {
var Q = [],
S = []; // Queue and Stack
// list of predcessors on shorteest paths from source
var pred = Object.create(null);
// distance from source
var dist = Object.create(null);
// number of shortest paths from source to key
var sigma = Object.create(null);
// dependency of source on key
var delta = Object.create(null);
var currentNode;
var centrality = Object.create(null);
graph.forEachNode(setCentralityToZero);
graph.forEachNode(calculateCentrality);
if (!oriented) {
// The centrality scores need to be divided by two if the graph is not oriented,
// since all shortest paths are considered twice
Object.keys(centrality).forEach(divideByTwo);
}
return centrality;
function divideByTwo(key) {
centrality[key] /= 2;
}
function setCentralityToZero(node) {
centrality[node.id] = 0;
}
function calculateCentrality(node) {
currentNode = node.id;
singleSourceShortestPath(currentNode);
accumulate();
}
function accumulate() {
graph.forEachNode(setDeltaToZero);
while (S.length) {
var w = S.pop();
var coeff = (1 + delta[w])/sigma[w];
var predcessors = pred[w];
for (var idx = 0; idx < predcessors.length; ++idx) {
var v = predcessors[idx];
delta[v] += sigma[v] * coeff;
}
if (w !== currentNode) {
centrality[w] += delta[w];
}
}
}
function setDeltaToZero(node) {
delta[node.id] = 0;
}
function singleSourceShortestPath(source) {
graph.forEachNode(initNode);
dist[source] = 0;
sigma[source] = 1;
Q.push(source);
while (Q.length) {
var v = Q.shift();
var dedup = Object.create(null);
S.push(v);
graph.forEachLinkedNode(v, toId, oriented);
}
function toId(otherNode) {
// NOTE: This code will also consider multi-edges, which are often
// ignored by popular software (Gephi/NetworkX). Depending on your use
// case this may not be desired and deduping needs to be performed. To
// save memory I'm not deduping here...
processNode(otherNode.id);
}
function initNode(node) {
var nodeId = node.id;
pred[nodeId] = []; // empty list
dist[nodeId] = -1;
sigma[nodeId] = 0;
}
function processNode(w) {
// path discovery
if (dist[w] === -1) {
// Node w is found for the first time
dist[w] = dist[v] + 1;
Q.push(w);
}
// path counting
if (dist[w] === dist[v] + 1) {
// edge (v, w) on a shortest path
sigma[w] += sigma[v];
pred[w].push(v);
}
}
}
}
},{}],5:[function(require,module,exports){
module.exports = degree;
/**
* Calculates graph nodes degree centrality (in/out or both).
*
* @see http://en.wikipedia.org/wiki/Centrality#Degree_centrality
*
* @param {ngraph.graph} graph object for which we are calculating centrality.
* @param {string} [kind=both] What kind of degree centrality needs to be calculated:
* 'in' - calculate in-degree centrality
* 'out' - calculate out-degree centrality
* 'inout' - (default) generic degree centrality is calculated
*/
function degree(graph, kind) {
var getNodeDegree,
sortedDegrees = [],
result = Object.create(null),
nodeDegree;
kind = (kind || 'both').toLowerCase();
if (kind === 'both' || kind === 'inout') {
getNodeDegree = inoutDegreeCalculator;
} else if (kind === 'in') {
getNodeDegree = inDegreeCalculator;
} else if (kind === 'out') {
getNodeDegree = outDegreeCalculator;
} else {
throw new Error('Expected centrality degree kind is: in, out or both');
}
graph.forEachNode(calculateNodeDegree);
return result;
function calculateNodeDegree(node) {
var links = graph.getLinks(node.id);
result[node.id] = getNodeDegree(links, node.id);
}
}
function inDegreeCalculator(links, nodeId) {
var total = 0;
for (var i = 0; i < links.length; i += 1) {
total += (links[i].toId === nodeId) ? 1 : 0;
}
return total;
}
function outDegreeCalculator(links, nodeId) {
var total = 0;
for (var i = 0; i < links.length; i += 1) {
total += (links[i].fromId === nodeId) ? 1 : 0;
}
return total;
}
function inoutDegreeCalculator(links) {
return links.length;
}
},{}],6:[function(require,module,exports){
module.exports = function(subject) {
validateSubject(subject);
var eventsStorage = createEventsStorage(subject);
subject.on = eventsStorage.on;
subject.off = eventsStorage.off;
subject.fire = eventsStorage.fire;
return subject;
};
function createEventsStorage(subject) {
// Store all event listeners to this hash. Key is event name, value is array
// of callback records.
//
// A callback record consists of callback function and its optional context:
// { 'eventName' => [{callback: function, ctx: object}] }
var registeredEvents = Object.create(null);
return {
on: function (eventName, callback, ctx) {
if (typeof callback !== 'function') {
throw new Error('callback is expected to be a function');
}
var handlers = registeredEvents[eventName];
if (!handlers) {
handlers = registeredEvents[eventName] = [];
}
handlers.push({callback: callback, ctx: ctx});
return subject;
},
off: function (eventName, callback) {
var wantToRemoveAll = (typeof eventName === 'undefined');
if (wantToRemoveAll) {
// Killing old events storage should be enough in this case:
registeredEvents = Object.create(null);
return subject;
}
if (registeredEvents[eventName]) {
var deleteAllCallbacksForEvent = (typeof callback !== 'function');
if (deleteAllCallbacksForEvent) {
delete registeredEvents[eventName];
} else {
var callbacks = registeredEvents[eventName];
for (var i = 0; i < callbacks.length; ++i) {
if (callbacks[i].callback === callback) {
callbacks.splice(i, 1);
}
}
}
}
return subject;
},
fire: function (eventName) {
var callbacks = registeredEvents[eventName];
if (!callbacks) {
return subject;
}
var fireArguments;
if (arguments.length > 1) {
fireArguments = Array.prototype.splice.call(arguments, 1);
}
for(var i = 0; i < callbacks.length; ++i) {
var callbackInfo = callbacks[i];
callbackInfo.callback.apply(callbackInfo.ctx, fireArguments);
}
return subject;
}
};
}
function validateSubject(subject) {
if (!subject) {
throw new Error('Eventify cannot use falsy object as events subject');
}
var reservedWords = ['on', 'fire', 'off'];
for (var i = 0; i < reservedWords.length; ++i) {
if (subject.hasOwnProperty(reservedWords[i])) {
throw new Error("Subject cannot be eventified, since it already has property '" + reservedWords[i] + "'");
}
}
}
},{}],7:[function(require,module,exports){
module.exports = createLayout;
module.exports.simulator = require('ngraph.physics.simulator');
/**
* Creates force based layout for a given graph.
* @param {ngraph.graph} graph which needs to be laid out
* @param {object} physicsSettings if you need custom settings
* for physics simulator you can pass your own settings here. If it's not passed
* a default one will be created.
*/
function createLayout(graph, physicsSettings) {
if (!graph) {
throw new Error('Graph structure cannot be undefined');
}
var createSimulator = require('ngraph.physics.simulator');
var physicsSimulator = createSimulator(physicsSettings);
var nodeBodies = typeof Object.create === 'function' ? Object.create(null) : {};
var springs = {};
var springTransform = physicsSimulator.settings.springTransform || noop;
// Initialize physical objects according to what we have in the graph:
initPhysics();
listenToGraphEvents();
var api = {
/**
* Performs one step of iterative layout algorithm
*/
step: function() {
return physicsSimulator.step();
},
/**
* For a given `nodeId` returns position
*/
getNodePosition: function (nodeId) {
return getInitializedBody(nodeId).pos;
},
/**
* Sets position of a node to a given coordinates
* @param {string} nodeId node identifier
* @param {number} x position of a node
* @param {number} y position of a node
* @param {number=} z position of node (only if applicable to body)
*/
setNodePosition: function (nodeId) {
var body = getInitializedBody(nodeId);
body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1));
},
/**
* @returns {Object} Link position by link id
* @returns {Object.from} {x, y} coordinates of link start
* @returns {Object.to} {x, y} coordinates of link end
*/
getLinkPosition: function (linkId) {
var spring = springs[linkId];
if (spring) {
return {
from: spring.from.pos,
to: spring.to.pos
};
}
},
/**
* @returns {Object} area required to fit in the graph. Object contains
* `x1`, `y1` - top left coordinates
* `x2`, `y2` - bottom right coordinates
*/
getGraphRect: function () {
return physicsSimulator.getBBox();
},
/*
* Requests layout algorithm to pin/unpin node to its current position
* Pinned nodes should not be affected by layout algorithm and always
* remain at their position
*/
pinNode: function (node, isPinned) {
var body = getInitializedBody(node.id);
body.isPinned = !!isPinned;
},
/**
* Checks whether given graph's node is currently pinned
*/
isNodePinned: function (node) {
return getInitializedBody(node.id).isPinned;
},
/**
* Request to release all resources
*/
dispose: function() {
graph.off('changed', onGraphChanged);
},
/**
* Gets physical body for a given node id. If node is not found undefined
* value is returned.
*/
getBody: getBody,
/**
* Gets spring for a given edge.
*
* @param {string} linkId link identifer. If two arguments are passed then
* this argument is treated as formNodeId
* @param {string=} toId when defined this parameter denotes head of the link
* and first argument is trated as tail of the link (fromId)
*/
getSpring: getSpring,
/**
* [Read only] Gets current physics simulator
*/
simulator: physicsSimulator
};
return api;
function getSpring(fromId, toId) {
var linkId;
if (toId === undefined) {
if (typeof fromId === 'string') {
// assume fromId as a linkId:
linkId = fromId;
} else {
// assume fromId to be a link object:
linkId = fromId.id;
}
} else {
// toId is defined, should grab link:
var link = graph.hasLink(fromId, toId);
if (!link) return;
linkId = link.id;
}
return springs[linkId];
}
function getBody(nodeId) {
return nodeBodies[nodeId];
}
function listenToGraphEvents() {
graph.on('changed', onGraphChanged);
}
function onGraphChanged(changes) {
for (var i = 0; i < changes.length; ++i) {
var change = changes[i];
if (change.changeType === 'add') {
if (change.node) {
initBody(change.node.id);
}
if (change.link) {
initLink(change.link);
}
} else if (change.changeType === 'remove') {
if (change.node) {
releaseNode(change.node);
}
if (change.link) {
releaseLink(change.link);
}
}
}
}
function initPhysics() {
graph.forEachNode(function (node) {
initBody(node.id);
});
graph.forEachLink(initLink);
}
function initBody(nodeId) {
var body = nodeBodies[nodeId];
if (!body) {
var node = graph.getNode(nodeId);
if (!node) {
throw new Error('initBody() was called with unknown node id');
}
var pos = node.position;
if (!pos) {
var neighbors = getNeighborBodies(node);
pos = physicsSimulator.getBestNewBodyPosition(neighbors);
}
body = physicsSimulator.addBodyAt(pos, node.data);
nodeBodies[nodeId] = body;
updateBodyMass(nodeId);
if (isNodeOriginallyPinned(node)) {
body.isPinned = true;
}
}
}
function releaseNode(node) {
var nodeId = node.id;
var body = nodeBodies[nodeId];
if (body) {
nodeBodies[nodeId] = null;
delete nodeBodies[nodeId];
physicsSimulator.removeBody(body);
}
}
function initLink(link) {
updateBodyMass(link.fromId);
updateBodyMass(link.toId);
var fromBody = nodeBodies[link.fromId],
toBody = nodeBodies[link.toId],
spring = physicsSimulator.addSpring(fromBody, toBody, link.length);
springTransform(link, spring);
springs[link.id] = spring;
}
function releaseLink(link) {
var spring = springs[link.id];
if (spring) {
var from = graph.getNode(link.fromId),
to = graph.getNode(link.toId);
if (from) updateBodyMass(from.id);
if (to) updateBodyMass(to.id);
delete springs[link.id];
physicsSimulator.removeSpring(spring);
}
}
function getNeighborBodies(node) {
// TODO: Could probably be done better on memory
var neighbors = [];
if (!node.links) {
return neighbors;
}
var maxNeighbors = Math.min(node.links.length, 2);
for (var i = 0; i < maxNeighbors; ++i) {
var link = node.links[i];
var otherBody = link.fromId !== node.id ? nodeBodies[link.fromId] : nodeBodies[link.toId];
if (otherBody && otherBody.pos) {
neighbors.push(otherBody);
}
}
return neighbors;
}
function updateBodyMass(nodeId) {
var body = nodeBodies[nodeId];
body.mass = nodeMass(nodeId);
}
/**
* Checks whether graph node has in its settings pinned attribute,
* which means layout algorithm cannot move it. Node can be preconfigured
* as pinned, if it has "isPinned" attribute, or when node.data has it.
*
* @param {Object} node a graph node to check
* @return {Boolean} true if node should be treated as pinned; false otherwise.
*/
function isNodeOriginallyPinned(node) {
return (node && (node.isPinned || (node.data && node.data.isPinned)));
}
function getInitializedBody(nodeId) {
var body = nodeBodies[nodeId];
if (!body) {
initBody(nodeId);
body = nodeBodies[nodeId];
}
return body;
}
/**
* Calculates mass of a body, which corresponds to node with given id.
*
* @param {String|Number} nodeId identifier of a node, for which body mass needs to be calculated
* @returns {Number} recommended mass of the body;
*/
function nodeMass(nodeId) {
return 1 + graph.getLinks(nodeId).length / 3.0;
}
}
function noop() { }
},{"ngraph.physics.simulator":8}],8:[function(require,module,exports){
/**
* Manages a simulation of physical forces acting on bodies and springs.
*/
module.exports = physicsSimulator;
function physicsSimulator(settings) {
var Spring = require('./lib/spring');
var expose = require('ngraph.expose');
var merge = require('ngraph.merge');
settings = merge(settings, {
/**
* Ideal length for links (springs in physical model).
*/
springLength: 30,
/**
* Hook's law coefficient. 1 - solid spring.
*/
springCoeff: 0.0008,
/**
* Coulomb's law coefficient. It's used to repel nodes thus should be negative
* if you make it positive nodes start attract each other :).
*/
gravity: -1.2,
/**
* Theta coefficient from Barnes Hut simulation. Ranged between (0, 1).
* The closer it's to 1 the more nodes algorithm will have to go through.
* Setting it to one makes Barnes Hut simulation no different from
* brute-force forces calculation (each node is considered).
*/
theta: 0.8,
/**
* Drag force coefficient. Used to slow down system, thus should be less than 1.
* The closer it is to 0 the less tight system will be.
*/
dragCoeff: 0.02,
/**
* Default time step (dt) for forces integration
*/
timeStep : 20,
/**
* Maximum movement of the system which can be considered as stabilized
*/
stableThreshold: 0.009
});
// We allow clients to override basic factory methods:
var createQuadTree = settings.createQuadTree || require('ngraph.quadtreebh');
var createBounds = settings.createBounds || require('./lib/bounds');
var createDragForce = settings.createDragForce || require('./lib/dragForce');
var createSpringForce = settings.createSpringForce || require('./lib/springForce');
var integrate = settings.integrator || require('./lib/eulerIntegrator');
var createBody = settings.createBody || require('./lib/createBody');
var bodies = [], // Bodies in this simulation.
springs = [], // Springs in this simulation.
quadTree = createQuadTree(settings),
bounds = createBounds(bodies, settings),
springForce = createSpringForce(settings),
dragForce = createDragForce(settings);
var publicApi = {
/**
* Array of bodies, registered with current simulator
*
* Note: To add new body, use addBody() method. This property is only
* exposed for testing/performance purposes.
*/
bodies: bodies,
/**
* Array of springs, registered with current simulator
*
* Note: To add new spring, use addSpring() method. This property is only
* exposed for testing/performance purposes.
*/
springs: springs,
/**
* Returns settings with which current simulator was initialized
*/
settings: settings,
/**
* Performs one step of force simulation.
*
* @returns {boolean} true if system is considered stable; False otherwise.
*/
step: function () {
accumulateForces();
var totalMovement = integrate(bodies, settings.timeStep);
bounds.update();
return totalMovement < settings.stableThreshold;
},
/**
* Adds body to the system at given position
*
* @param {Object} pos position of a body
*
* @returns {ngraph.physics.primitives.Body} added body
*/
addBodyAt: function (pos, data) {
if (!pos) {
throw new Error('Body position is required');
}
var body = createBody(pos);
body["data"] = data;
bodies.push(body);
return body;
},
/**
* Removes body from the system
*
* @param {ngraph.physics.primitives.Body} body to remove
*
* @returns {Boolean} true if body found and removed. falsy otherwise;
*/
removeBody: function (body) {
if (!body) { return; }
var idx = bodies.indexOf(body);
if (idx < 0) { return; }
bodies.splice(idx, 1);
if (bodies.length === 0) {
bounds.reset();
}
return true;
},
/**
* Adds a spring to this simulation.
*
* @returns {Object} - a handle for a spring. If you want to later remove
* spring pass it to removeSpring() method.
*/
addSpring: function (body1, body2, springLength, springWeight, springCoefficient) {
if (!body1 || !body2) {
throw new Error('Cannot add null spring to force simulator');
}
if (typeof springLength !== 'number') {
springLength = -1; // assume global configuration
}
var spring = new Spring(body1, body2, springLength, springCoefficient >= 0 ? springCoefficient : -1, springWeight);
springs.push(spring);
// TODO: could mark simulator as dirty.
return spring;
},
/**
* Removes spring from the system
*
* @param {Object} spring to remove. Spring is an object returned by addSpring
*
* @returns {Boolean} true if spring found and removed. falsy otherwise;
*/
removeSpring: function (spring) {
if (!spring) { return; }
var idx = springs.indexOf(spring);
if (idx > -1) {
springs.splice(idx, 1);
return true;
}
},
getBestNewBodyPosition: function (neighbors) {
return bounds.getBestNewPosition(neighbors);
},
/**
* Returns bounding box which covers all bodies
*/
getBBox: function () {
return bounds.box;
},
gravity: function (value) {
if (value !== undefined) {
settings.gravity = value;
quadTree.options({gravity: value});
return this;
} else {
return settings.gravity;
}
},
theta: function (value) {
if (value !== undefined) {
settings.theta = value;
quadTree.options({theta: value});
return this;
} else {
return settings.theta;
}
}
};
// allow settings modification via public API:
expose(settings, publicApi);