xxxxxxxxxx
96
class Graph {
constructor() {
this.topics = {};
this.sites = {};
}
addNode(n) {
const key = n.link ? "sites" : "topics";
if (this.getNode(n.name) === null) {
this[key][n.name] = n;
}
}
getNode(name) {
let node = this.topics[name] || this.sites[name] || null;
return node;
}
listNodes() {
return [Object.values(this.sites), Object.values(this.topics)]
}
printGraph() {
return Object.values(this.topics)
.map((node) => node.printNode())
.join("\n");
}
drawGraph() {
for (let node of this.listNodes()) {
textAlign(CENTER)
text(node.name, node.coords.x, node.coords.y)
for (let edge of node.edges) {
stroke('rgba(0, 0, 0, 0.25)');
strokeWeight(1);
line(node.coords.x, node.coords.y, edge.coords.x, edge.coords.y)
}
}
}
calculateForces(node, others) {
let force = createVector()
let idealSpringDist = 50
let repulsionConstant = 10
let springConstant = 1
for (let other of others) {
if (node === other) {
continue
}
let toNode = p5.Vector.sub(node.coords, other.coords)
let toOther = p5.Vector.sub(other.coords, node.coords)
let distBetween = dist(node.coords.x,node.coords.y, other.coords.x, other.coords.y)
let repulsionForce = toNode.copy().mult(repulsionConstant/(distBetween*distBetween))
let attractionForce = toOther.copy().mult(springConstant * Math.log(distBetween/idealSpringDist))
let isEdge = node.edges.includes(other)
force.add(p5.Vector.sub(attractionForce, repulsionForce)).limit(3)
force.add(repulsionForce).limit(1)
}
return force
}
edges(node) {
let offScreen = {
top: node.coords.y < 0,
left: node.coords.x < 0,
bottom: node.coords.y > height,
right: node.coords.x > width,
}
if (offScreen.top) {
node.coords.y = 0
}
if (offScreen.left) {
node.coords.x = 0
}
if (offScreen.bottom) {
node.coords.y = height - 1
}
if (offScreen.right) {
node.coords.x = width - 1
}
}
relaxGraph() {
let moveNode = (node, force) => {
node.coords.add(p5.Vector.sub(force, node).limit(1))
}
let listOfNodes = this.listNodes()
for (let node of listOfNodes) {
let force = this.calculateForces(node, listOfNodes)
moveNode(node, force)
this.edges(node)
}
}
}