Added static projects sites to the blog.pull/27/head
@ -0,0 +1,143 @@ | |||||
<!DOCTYPE html> | |||||
<html lang="en"> | |||||
<head> | |||||
<meta charset="utf-8"> | |||||
<title>Jrtechs Steam Friend Graph Project</title> | |||||
<meta name="viewport" content="width=device-width, initial-scale=1"> | |||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |||||
<link rel="stylesheet" href="css/bootstrap.css" media="screen"> | |||||
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> | |||||
</head> | |||||
<body> | |||||
<div class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"> | |||||
<div class="container"> | |||||
<a class="navbar-brand" href="#">Steam Graph Project</a> | |||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> | |||||
<span class="navbar-toggler-icon"></span> | |||||
</button> | |||||
<div class="collapse navbar-collapse" id="navbarSupportedContent"> | |||||
<ul class="navbar-nav mr-auto"> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a> | |||||
</li> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="graphs.html">Graphs</a> | |||||
</li> | |||||
<!--<li class="nav-item">--> | |||||
<!--<a class="nav-link" href="profile.html">Profile Look-Up</a>--> | |||||
<!--</li>--> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="faq.html">FAQ</a> | |||||
</li> | |||||
</ul> | |||||
<ul class="nav navbar-nav navbar-right"> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.net">Blog</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.me">Resume</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://github.com/jrtechs">Github</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="container"> | |||||
<br><br><br> | |||||
<h2>My Steam websocket server down.</h2> | |||||
<p>Sorry about that, you should try again some other day.</p> | |||||
<img src="img/404.jpg"> | |||||
<br><br> | |||||
</div> | |||||
<!- | |||||
┈┈╱▔▔▔▔▔╲┈┈┈HM┈HM | |||||
┈╱┈┈╱▔╲╲╲▏┈┈┈HMMM | |||||
╱┈┈╱━╱▔▔▔▔▔╲━╮┈┈ | |||||
▏┈▕┃▕╱▔╲╱▔╲▕╮┃┈┈ | |||||
▏┈▕╰━▏▊▕▕▋▕▕━╯┈┈ | |||||
╲┈┈╲╱▔╭╮▔▔┳╲╲┈┈┈ | |||||
┈╲┈┈▏╭━━━━╯▕▕┈┈┈ | |||||
┈┈╲┈╲▂▂▂▂▂▂╱╱┈┈┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊┈┈┈╲┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊▕╲┈┈╲ | |||||
┈╱▔╲▏┊┈┈┈┈┊▕╱▔╲▕ | |||||
┈▏ ┈┈┈╰┈┈┈┈╯┈┈┈▕▕ | |||||
┈╲┈┈┈╲┈┈┈┈╱┈┈┈╱┈╲ | |||||
┈┈╲┈┈▕▔▔▔▔▏┈┈╱╲╲╲▏ | |||||
┈╱▔┈┈▕┈┈┈┈▏┈┈▔╲▔▔ | |||||
┈╲▂▂▂╱┈┈┈┈╲▂▂▂╱┈ | |||||
If you are seeing this monkey that means that you are interested in my | |||||
code. Yay!! If you are not here to hack me ... you should really consider | |||||
contributing to some of my public projects on github. | |||||
https://github.com/jrtechs | |||||
--> | |||||
<!-- Footer --> | |||||
<footer class="text-center"> | |||||
<div class="footer-above"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Location</h3> | |||||
<p>Rochester Institute of Technology | |||||
<br>1 Lomb Memorial Dr, Rochester, NY 14623</p> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Around the Web</h3> | |||||
<ul class="list-inline"> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://www.youtube.com/c/JrtechsNet"> | |||||
<i class="fa fa-fw fa-youtube"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://github.com/jrtechs"> | |||||
<i class="fa fa-fw fa-github"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="http://jrtechs.net"> | |||||
<i class="fa fa-fw fa-wordpress"></i> | |||||
</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>About This Website</h3> | |||||
<p>Check out the source code for this website on my | |||||
<a href="https://github.com/jrtechs">github</a>.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="footer-below"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="col-lg-12"> | |||||
<p class="m-0 text-center text-white"><a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank">CC-BY-SA 4.0</a> <script type="text/javascript"> | |||||
document.write(new Date().getFullYear()); | |||||
</script> Jrtechs</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</footer> | |||||
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> | |||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> | |||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> | |||||
</body> | |||||
</html> |
@ -0,0 +1,275 @@ | |||||
<!DOCTYPE html> | |||||
<html lang="en"> | |||||
<head> | |||||
<meta charset="utf-8"> | |||||
<title>Jrtechs Steam Friend Graph Project</title> | |||||
<meta name="viewport" content="width=device-width, initial-scale=1"> | |||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |||||
<link rel="stylesheet" href="css/bootstrap.css" media="screen"> | |||||
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> | |||||
</head> | |||||
<body> | |||||
<div class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"> | |||||
<div class="container"> | |||||
<a class="navbar-brand" href="#">Steam Graph Project</a> | |||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> | |||||
<span class="navbar-toggler-icon"></span> | |||||
</button> | |||||
<div class="collapse navbar-collapse" id="navbarSupportedContent"> | |||||
<ul class="navbar-nav mr-auto"> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="index.html">Home</a> | |||||
</li> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="graphs.html">Graphs<span class="sr-only">(current)</span></a> | |||||
</li> | |||||
<!--<li class="nav-item">--> | |||||
<!--<a class="nav-link" href="profile.html">Profile Look-Up</a>--> | |||||
<!--</li>--> | |||||
<li class="nav-item"> | |||||
<a class="nav-link active" href="faq.html">FAQ</a> | |||||
</li> | |||||
</ul> | |||||
<ul class="nav navbar-nav navbar-right"> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.net">Blog</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.me">Resume</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://github.com/jrtechs">Github</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="container"> | |||||
<br><br><br> | |||||
<h1 class="align-content-center">Frequently asked questions</h1> | |||||
<div class="card-group" id="faqAccordion"> | |||||
<div class="row w-100"> | |||||
<div class="card card-body "> | |||||
<div class="panel-heading accordion-toggle question-toggle collapsed" data-toggle="collapse" data-parent="#faqAccordion" data-target="#question0"> | |||||
<h4 class="panel-title"> | |||||
<a href="#" class="ing">Q: How do I get my Steam ID?</a> | |||||
</h4> | |||||
</div> | |||||
<div id="question0" class="panel-collapse collapse" style="height: 0px;"> | |||||
<div class="panel-body"> | |||||
<h5><span class="label label-primary">Answer</span> | |||||
</h5> | |||||
<p> | |||||
Option 1:<br> | |||||
If you have steam open, simply click on the profile which you would like to view | |||||
from your friends list. The steam ID will be in the url that appears in the steam | |||||
browser. | |||||
<img src="img/faq/steamIdOption2.png"> | |||||
</p> | |||||
<p> | |||||
Option 2:<br> | |||||
If you only know the steam username, you can use steam ID look up sites like | |||||
<a href="https://steamid.io/">STEAMID I/O</a>. For this website, you will want | |||||
to use the steamID64 number. | |||||
<img src="img/faq/steamId.png"> | |||||
</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="row w-100"> | |||||
<div class="card card-body "> | |||||
<div class="panel-heading accordion-toggle collapsed question-toggle" data-toggle="collapse" data-parent="#faqAccordion" data-target="#question1"> | |||||
<h4 class="panel-title"> | |||||
<a href="#" class="ing">Q: Why did you make this?</a> | |||||
</h4> | |||||
</div> | |||||
<div id="question1" class="panel-collapse collapse" style="height: 0px;"> | |||||
<div class="panel-body"> | |||||
<h5><span class="label label-primary">Answer</span></h5> | |||||
<p>Great question, I will get back to you on that one.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="row w-100"> | |||||
<div class="card card-body "> | |||||
<div class="panel-heading accordion-toggle collapsed question-toggle" data-toggle="collapse" data-parent="#faqAccordion" data-target="#question2"> | |||||
<h4 class="panel-title"> | |||||
<a href="#" class="ing">Q: Why is the back end written in Java?</a> | |||||
</h4> | |||||
</div> | |||||
<div id="question2" class="panel-collapse collapse" style="height: 0px;"> | |||||
<div class="panel-body"> | |||||
<h5><span class="label label-primary">Answer</span></h5> | |||||
<p>Contrary to popular belief, Java is not a <i>terrible</i> language. For this project | |||||
I needed something that was easy to work with a Gremlin database -- the tinkerpop framework makes | |||||
this very convenient. Overall, I needed a backend because I cannot dish out my steam api key to users. | |||||
Plus, this way I can cache steam friends making graph creation times faster.</p> | |||||
<img src="img/faq/java.png"> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="row w-100"> | |||||
<div class="card card-body "> | |||||
<div class="panel-heading accordion-toggle collapsed question-toggle" data-toggle="collapse" data-parent="#faqAccordion" data-target="#question3"> | |||||
<h4 class="panel-title"> | |||||
<a href="#" class="ing">Q: Does steam really allow you to do this?</a> | |||||
</h4> | |||||
</div> | |||||
<div id="question3" class="panel-collapse collapse" style="height: 0px;"> | |||||
<div class="panel-body"> | |||||
<h5><span class="label label-primary">Answer</span></h5> | |||||
<p>Yes. You can read all about Steam's API usage <a href="https://steamcommunity.com/dev/apiterms">here</a>.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="row w-100"> | |||||
<div class="card card-body "> | |||||
<div class="panel-heading accordion-toggle collapsed question-toggle" data-toggle="collapse" data-parent="#faqAccordion" data-target="#question5"> | |||||
<h4 class="panel-title"> | |||||
<a href="#" class="ing">Q: Can I run my own Steam friend graph server?</a> | |||||
</h4> | |||||
</div> | |||||
<div id="question5" class="panel-collapse collapse" style="height: 0px;"> | |||||
<div class="panel-body"> | |||||
<h5><span class="label label-primary">Answer</span></h5> | |||||
<p>Go for it, all the code is on <a href="https://github.com/jrtechs/SteamFriendsGraph">GitHub</a>. I am going to be making a "comprehensive" docs which | |||||
should explain how to run this.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="row w-100"> | |||||
<div class="card card-body "> | |||||
<div class="panel-heading accordion-toggle collapsed question-toggle" data-toggle="collapse" data-parent="#faqAccordion" data-target="#question6"> | |||||
<h4 class="panel-title"> | |||||
<a href="#" class="ing">Q: Why do I not see all my friends?</a> | |||||
</h4> | |||||
</div> | |||||
<div id="question6" class="panel-collapse collapse" style="height: 0px;"> | |||||
<div class="panel-body"> | |||||
<h5><span class="label label-primary">Answer</span></h5> | |||||
<p>Since the server caches all the friend requests in a local graph database, it is possible to | |||||
not see all your friends if you recently added them. I am working on a solution to this, | |||||
however, I don't want to excessively hammer the steam API if I don't have to.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<br> | |||||
<center><img class="w-50" src="img/faq/faqGraph.png" /></center> | |||||
<br> | |||||
</div> | |||||
<!- | |||||
┈┈╱▔▔▔▔▔╲┈┈┈HM┈HM | |||||
┈╱┈┈╱▔╲╲╲▏┈┈┈HMMM | |||||
╱┈┈╱━╱▔▔▔▔▔╲━╮┈┈ | |||||
▏┈▕┃▕╱▔╲╱▔╲▕╮┃┈┈ | |||||
▏┈▕╰━▏▊▕▕▋▕▕━╯┈┈ | |||||
╲┈┈╲╱▔╭╮▔▔┳╲╲┈┈┈ | |||||
┈╲┈┈▏╭━━━━╯▕▕┈┈┈ | |||||
┈┈╲┈╲▂▂▂▂▂▂╱╱┈┈┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊┈┈┈╲┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊▕╲┈┈╲ | |||||
┈╱▔╲▏┊┈┈┈┈┊▕╱▔╲▕ | |||||
┈▏ ┈┈┈╰┈┈┈┈╯┈┈┈▕▕ | |||||
┈╲┈┈┈╲┈┈┈┈╱┈┈┈╱┈╲ | |||||
┈┈╲┈┈▕▔▔▔▔▏┈┈╱╲╲╲▏ | |||||
┈╱▔┈┈▕┈┈┈┈▏┈┈▔╲▔▔ | |||||
┈╲▂▂▂╱┈┈┈┈╲▂▂▂╱┈ | |||||
If you are seeing this monkey that means that you are interested in my | |||||
code. Yay!! If you are not here to hack me ... you should really consider | |||||
contributing to some of my public projects on github. | |||||
https://github.com/jrtechs | |||||
--> | |||||
<!-- Footer --> | |||||
<footer class="text-center"> | |||||
<div class="footer-above"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Location</h3> | |||||
<p>Rochester Institute of Technology | |||||
<br>1 Lomb Memorial Dr, Rochester, NY 14623</p> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Around the Web</h3> | |||||
<ul class="list-inline"> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://www.youtube.com/c/JrtechsNet"> | |||||
<i class="fa fa-fw fa-youtube"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://github.com/jrtechs"> | |||||
<i class="fa fa-fw fa-github"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="http://jrtechs.net"> | |||||
<i class="fa fa-fw fa-wordpress"></i> | |||||
</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>About This Website</h3> | |||||
<p>Check out the source code for this website on my | |||||
<a href="https://github.com/jrtechs">github</a>.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="footer-below"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="col-lg-12"> | |||||
<p class="m-0 text-center text-white"><a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank">CC-BY-SA 4.0</a> <script type="text/javascript"> | |||||
document.write(new Date().getFullYear()); | |||||
</script> Jrtechs</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</footer> | |||||
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> | |||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> | |||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> | |||||
</body> | |||||
</html> |
@ -0,0 +1,432 @@ | |||||
<!DOCTYPE html> | |||||
<html lang="en"> | |||||
<head> | |||||
<meta charset="utf-8"> | |||||
<title>Jrtechs Steam Friend Graph Project</title> | |||||
<meta name="viewport" content="width=device-width, initial-scale=1"> | |||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |||||
<link rel="stylesheet" href="css/bootstrap.css" media="screen"> | |||||
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> | |||||
<script src="src/sigma.core.js"></script> | |||||
<script src="src/conrad.js"></script> | |||||
<script src="src/utils/sigma.utils.js"></script> | |||||
<script src="src/utils/sigma.polyfills.js"></script> | |||||
<script src="src/sigma.settings.js"></script> | |||||
<script src="src/classes/sigma.classes.dispatcher.js"></script> | |||||
<script src="src/classes/sigma.classes.configurable.js"></script> | |||||
<script src="src/classes/sigma.classes.graph.js"></script> | |||||
<script src="src/classes/sigma.classes.camera.js"></script> | |||||
<script src="src/classes/sigma.classes.quad.js"></script> | |||||
<script src="src/classes/sigma.classes.edgequad.js"></script> | |||||
<script src="src/captors/sigma.captors.mouse.js"></script> | |||||
<script src="src/captors/sigma.captors.touch.js"></script> | |||||
<script src="src/renderers/sigma.renderers.canvas.js"></script> | |||||
<script src="src/renderers/sigma.renderers.webgl.js"></script> | |||||
<script src="src/renderers/sigma.renderers.svg.js"></script> | |||||
<script src="src/renderers/sigma.renderers.def.js"></script> | |||||
<script src="src/renderers/webgl/sigma.webgl.nodes.def.js"></script> | |||||
<script src="src/renderers/webgl/sigma.webgl.nodes.fast.js"></script> | |||||
<script src="src/renderers/webgl/sigma.webgl.edges.def.js"></script> | |||||
<script src="src/renderers/webgl/sigma.webgl.edges.fast.js"></script> | |||||
<script src="src/renderers/webgl/sigma.webgl.edges.arrow.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.labels.def.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.hovers.def.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.nodes.def.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edges.def.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edges.curve.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edges.arrow.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edges.curvedArrow.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edgehovers.def.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edgehovers.curve.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edgehovers.arrow.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.edgehovers.curvedArrow.js"></script> | |||||
<script src="src/renderers/canvas/sigma.canvas.extremities.def.js"></script> | |||||
<script src="src/renderers/svg/sigma.svg.utils.js"></script> | |||||
<script src="src/renderers/svg/sigma.svg.nodes.def.js"></script> | |||||
<script src="src/renderers/svg/sigma.svg.edges.def.js"></script> | |||||
<script src="src/renderers/svg/sigma.svg.edges.curve.js"></script> | |||||
<script src="src/renderers/svg/sigma.svg.labels.def.js"></script> | |||||
<script src="src/renderers/svg/sigma.svg.hovers.def.js"></script> | |||||
<script src="src/middlewares/sigma.middlewares.rescale.js"></script> | |||||
<script src="src/middlewares/sigma.middlewares.copy.js"></script> | |||||
<script src="src/misc/sigma.misc.animation.js"></script> | |||||
<script src="src/misc/sigma.misc.bindEvents.js"></script> | |||||
<script src="src/misc/sigma.misc.bindDOMEvents.js"></script> | |||||
<script src="src/misc/sigma.misc.drawHovers.js"></script> | |||||
<script src="src/plugins/sigma.plugins.neighborhoods/sigma.plugins.neighborhoods.js"></script> | |||||
<script src="src/plugins/sigma.layout.forceAtlas2/supervisor.js"></script> | |||||
<script src="src/plugins/sigma.layout.forceAtlas2/worker.js"></script> | |||||
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> | |||||
</head> | |||||
<body> | |||||
<div class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"> | |||||
<div class="container"> | |||||
<a class="navbar-brand" href="#">Steam Graph Project</a> | |||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> | |||||
<span class="navbar-toggler-icon"></span> | |||||
</button> | |||||
<div class="collapse navbar-collapse" id="navbarSupportedContent"> | |||||
<ul class="navbar-nav mr-auto"> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="index.html">Home</a> | |||||
</li> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="graphs.html">Graphs<span class="sr-only">(current)</span></a> | |||||
</li> | |||||
<!--<li class="nav-item">--> | |||||
<!--<a class="nav-link" href="profile.html">Profile Look-Up</a>--> | |||||
<!--</li>--> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="faq.html">FAQ</a> | |||||
</li> | |||||
</ul> | |||||
<ul class="nav navbar-nav navbar-right"> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.net">Blog</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.me">Resume</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://github.com/jrtechs">Github</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<!-- END SIGMA IMPORTS --> | |||||
<div id="container"> | |||||
<style> | |||||
#graph-container { | |||||
top: 0; | |||||
bottom: 0; | |||||
left: 0; | |||||
right: 0; | |||||
position: absolute; | |||||
background-color: #455660; | |||||
} | |||||
.sigma-edge { | |||||
stroke: #14191C; | |||||
fill-opacity: 0.7; | |||||
stroke-opacity: 0.7; | |||||
} | |||||
.sigma-node { | |||||
fill: #008080; | |||||
stroke: #14191C; | |||||
stroke-width: 2px; | |||||
} | |||||
.sigma-node:hover { | |||||
fill: blue; | |||||
} | |||||
.sigma-label | |||||
{ | |||||
fill: #00CED1 !important; | |||||
} | |||||
.muted { | |||||
fill-opacity: 0.1; | |||||
stroke-opacity: 0.1; | |||||
} | |||||
</style> | |||||
<div id="graph-container" style="width:100%; height:100%"></div> | |||||
</div> | |||||
<script> | |||||
var s; | |||||
var g = { | |||||
nodes: [], | |||||
edges: [] | |||||
}; | |||||
/** | |||||
* Creates a new sigma graph | |||||
*/ | |||||
s = new sigma({ | |||||
graph: g, | |||||
settings: { | |||||
enableHovering: false | |||||
} | |||||
}); | |||||
/** | |||||
* Sets the sigma graph to render using svg | |||||
*/ | |||||
s.addRenderer({ | |||||
id: 'main', | |||||
type: 'svg', | |||||
container: document.getElementById('graph-container'), | |||||
freeStyle: true | |||||
}); | |||||
/** | |||||
* Simple function to get the get data from the url | |||||
*/ | |||||
function getUrlVars() | |||||
{ | |||||
var vars = {}; | |||||
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, | |||||
function(m,key,value) { | |||||
vars[key] = value; | |||||
}); | |||||
return vars; | |||||
} | |||||
/** Web socket to communicate with the steam friend java server */ | |||||
connection = new WebSocket('ws://steam.student.rit.edu:4444'); | |||||
setTimeout(function() | |||||
{ | |||||
if (this.connection.readyState != 1) | |||||
{ | |||||
document.location.href = "error.html"; | |||||
} | |||||
}, 6000); | |||||
/** | |||||
* When the web socket is opened, this function | |||||
* fetches the get data and requests the server | |||||
* to start giving it graph information | |||||
*/ | |||||
connection.onopen = function () | |||||
{ | |||||
var getData = getUrlVars(); | |||||
if(getData["id"] != undefined && getData["id"] != "") | |||||
{ | |||||
connection.send("{id:'" + getData["id"] + "', graph:" + | |||||
getData["graph"] + "}"); | |||||
connection.send("{go:1}"); | |||||
} | |||||
else | |||||
{ | |||||
connection.close(); | |||||
} | |||||
}; | |||||
/** | |||||
* Logs any errors with the web socket -- usually error | |||||
* connecting to the server | |||||
* @param error | |||||
*/ | |||||
connection.onerror = function (error) | |||||
{ | |||||
console.log('WebSocket Error ' + error); | |||||
}; | |||||
/** | |||||
* Helper function to add a new node to the sigma graph | |||||
* | |||||
* @param request | |||||
*/ | |||||
function addNodeToGraph(request) | |||||
{ | |||||
if(s.graph.nodes(request.id) == undefined) | |||||
{ | |||||
s.graph.addNode({ | |||||
id: request.id, | |||||
label: request.name, | |||||
x: request.x, | |||||
y: request.y, | |||||
size: request.size | |||||
}); | |||||
s.refresh(); | |||||
} | |||||
} | |||||
/** | |||||
* Helper function to add an edge between two nodes on the | |||||
* sigma graph | |||||
* | |||||
* @param request | |||||
*/ | |||||
function addEdgeToGraph(request) | |||||
{ | |||||
s.graph.addEdge({ | |||||
id: request.id, | |||||
source: request.p1, | |||||
target: request.p2, | |||||
size: 1 | |||||
}); | |||||
s.refresh(); | |||||
} | |||||
/** | |||||
* Parses any events from the server | |||||
* action 1: add a new node to the graph | |||||
* action 2: add a new edge to the graph | |||||
* action 3: start applying forces to the graph | |||||
* | |||||
* @param e | |||||
*/ | |||||
connection.onmessage = function (e) | |||||
{ | |||||
var request = JSON.parse(e.data); | |||||
if(request.action == 1) | |||||
{ | |||||
setTimeout(function() | |||||
{ | |||||
addNodeToGraph(request); | |||||
connection.send("{go:1}"); | |||||
}, 0); | |||||
} | |||||
else if(request.action == 2) | |||||
{ | |||||
setTimeout(function() | |||||
{ | |||||
addEdgeToGraph(request); | |||||
connection.send("{go:1}"); | |||||
}, 0); | |||||
} | |||||
else if(request.action == 3) | |||||
{ | |||||
var getData = getUrlVars(); | |||||
if(getData["graph"] == 2) | |||||
{ | |||||
s.startForceAtlas2({worker: true, barnesHutOptimize: false, | |||||
scalingRatio: 3, slowDown: 5, gravity: 10}); | |||||
setTimeout(function () { | |||||
s.stopForceAtlas2(); | |||||
}, 15000); | |||||
} | |||||
else | |||||
{ | |||||
s.startForceAtlas2({worker: true, barnesHutOptimize: false, | |||||
scalingRatio: 6, slowDown: 4, gravity: 40}); | |||||
setTimeout(function () { | |||||
s.stopForceAtlas2(); | |||||
}, 30000); | |||||
} | |||||
} | |||||
else if(request.action == -1) | |||||
{ | |||||
alert("The provided steamID was invalid."); | |||||
} | |||||
}; | |||||
// Binding silly interactions | |||||
function mute(node) | |||||
{ | |||||
if (!~node.getAttribute('class').search(/muted/)) | |||||
node.setAttributeNS(null, 'class', | |||||
node.getAttribute('class') + ' muted'); | |||||
} | |||||
function unmute(node) | |||||
{ | |||||
node.setAttributeNS(null, 'class', | |||||
node.getAttribute('class').replace(/(\s|^)muted(\s|$)/g, '$2')); | |||||
} | |||||
/** | |||||
* jquery stuff for hiding and displaying users when clicked | |||||
*/ | |||||
s.bind('clickNode doubleClickNode rightClickNode', function(e) | |||||
{ | |||||
$('.sigma-node, .sigma-edge, .sigma-label').each(function() | |||||
{ | |||||
mute(this); | |||||
}); | |||||
var neighbors = s.graph.neighborhood(e.data.node.id); | |||||
neighbors.nodes.forEach(function(node) | |||||
{ | |||||
unmute($('[data-node-id="' + node.id + '"]')[0]); | |||||
unmute($('[data-label-target="' + node.id + '"]')[0]); | |||||
}); | |||||
neighbors.edges.forEach(function(edge) { | |||||
unmute($('[data-edge-id="' + edge.id + '"]')[0]); | |||||
}); | |||||
}); | |||||
$('.sigma-node').click(function() | |||||
{ | |||||
$('.sigma-node, .sigma-edge').each(function() | |||||
{ | |||||
mute(this); | |||||
}); | |||||
// Unmuting neighbors | |||||
var neighbors = s.graph.neighborhood($(this).attr('data-node-id')); | |||||
neighbors.nodes.forEach(function(node) | |||||
{ | |||||
unmute($('[data-node-id="' + node.id + '"]')[0]); | |||||
unmute($('[data-label-target="' + node.id + '"]')[0]); | |||||
}); | |||||
neighbors.edges.forEach(function(edge) | |||||
{ | |||||
unmute($('[data-edge-id="' + edge.id + '"]')[0]); | |||||
}); | |||||
}); | |||||
s.bind('clickStage', function() | |||||
{ | |||||
$('.sigma-node, .sigma-edge, .sigma-label').each(function() | |||||
{ | |||||
unmute(this); | |||||
}); | |||||
}); | |||||
</script> | |||||
<!- | |||||
┈┈╱▔▔▔▔▔╲┈┈┈HM┈HM | |||||
┈╱┈┈╱▔╲╲╲▏┈┈┈HMMM | |||||
╱┈┈╱━╱▔▔▔▔▔╲━╮┈┈ | |||||
▏┈▕┃▕╱▔╲╱▔╲▕╮┃┈┈ | |||||
▏┈▕╰━▏▊▕▕▋▕▕━╯┈┈ | |||||
╲┈┈╲╱▔╭╮▔▔┳╲╲┈┈┈ | |||||
┈╲┈┈▏╭━━━━╯▕▕┈┈┈ | |||||
┈┈╲┈╲▂▂▂▂▂▂╱╱┈┈┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊┈┈┈╲┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊▕╲┈┈╲ | |||||
┈╱▔╲▏┊┈┈┈┈┊▕╱▔╲▕ | |||||
┈▏ ┈┈┈╰┈┈┈┈╯┈┈┈▕▕ | |||||
┈╲┈┈┈╲┈┈┈┈╱┈┈┈╱┈╲ | |||||
┈┈╲┈┈▕▔▔▔▔▏┈┈╱╲╲╲▏ | |||||
┈╱▔┈┈▕┈┈┈┈▏┈┈▔╲▔▔ | |||||
┈╲▂▂▂╱┈┈┈┈╲▂▂▂╱┈ | |||||
If you are seeing this monkey that means that you are interested in my | |||||
code. Yay!! If you are not here to hack me ... you should really consider | |||||
contributing to some of my public projects on github. | |||||
https://github.com/jrtechs | |||||
--> | |||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> | |||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> | |||||
</body> | |||||
</html> | |||||
@ -0,0 +1,214 @@ | |||||
<!DOCTYPE html> | |||||
<html lang="en"> | |||||
<head> | |||||
<meta charset="utf-8"> | |||||
<title>Jrtechs Steam Friend Graph Project</title> | |||||
<meta name="viewport" content="width=device-width, initial-scale=1"> | |||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |||||
<link rel="stylesheet" href="css/bootstrap.css" media="screen"> | |||||
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> | |||||
</head> | |||||
<body> | |||||
<div class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"> | |||||
<div class="container"> | |||||
<a class="navbar-brand" href="#">Steam Graph Project</a> | |||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> | |||||
<span class="navbar-toggler-icon"></span> | |||||
</button> | |||||
<div class="collapse navbar-collapse" id="navbarSupportedContent"> | |||||
<ul class="navbar-nav mr-auto"> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="index.html">Home</a> | |||||
</li> | |||||
<li class="nav-item active"> | |||||
<a class="nav-link" href="graphs.html">Graphs<span class="sr-only">(current)</span></a> | |||||
</li> | |||||
<!--<li class="nav-item">--> | |||||
<!--<a class="nav-link" href="profile.html">Profile Look-Up</a>--> | |||||
<!--</li>--> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="faq.html">FAQ</a> | |||||
</li> | |||||
</ul> | |||||
<ul class="nav navbar-nav navbar-right"> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.net">Blog</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.me">Resume</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://github.com/jrtechs">Github</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="container"> | |||||
<br><br><br> | |||||
<div class="row"> | |||||
<div class="col-8"> | |||||
<div class="card mb-3"> | |||||
<div class="card-header"><h2>How To Make a Graph</h2></div> | |||||
<div class="card-body"> | |||||
<h4>Overview</h4> | |||||
<p class="card-text">Using the form on this page, you enter your steamID and select the | |||||
graph type you wish to use and then press generate. This will take you to a | |||||
new page where your graph will render. Rendering will take between 1-4 minutes depending | |||||
on how many friends you have on your graph. Once all the friends are on the graph, it will | |||||
shake bringing it to its "final form".</p> | |||||
<h4>SteamID</h4> | |||||
<p> | |||||
Every steam user has an unique ID. This is NOT your username. | |||||
If you have steam open, simply click on the profile which you would like to view | |||||
from your friends list. The steam ID will be in the url that appears in the steam | |||||
browser. | |||||
<br> | |||||
<img src="img/faq/steamIdOption2.png" alt="Steam id in steam browser"> | |||||
</p> | |||||
<h4>Graph Types</h4> | |||||
<ul> | |||||
<li> | |||||
<h5>Friends of Friends Graph</h5> | |||||
<p> | |||||
This graph will display all of your friends in addition to all of their friends. | |||||
<br>ex:<br> | |||||
<img src="img/jrtechs1.png" alt="friends of friends steam graph" width="100%"> | |||||
</p> | |||||
</li> | |||||
<li> | |||||
<h5>Common Friends Graph</h5> | |||||
<p> | |||||
This graph will only display your friends, however, it will draw edges between your friends | |||||
if they are friends with each other. | |||||
<br>ex:<br> | |||||
<img src="img/jrtechs2.png" alt="Common friends steam graph" width="100%"> | |||||
</p> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="col-4"> | |||||
<div class="card w-100" style="width: 18rem; background-color:#455660;"> | |||||
<img class="card-img-top" src="img/banner2.png"> | |||||
<div class="card-body"> | |||||
<form action="graph.html" method="get"> | |||||
<div class="form-group row"> | |||||
<!--<label for="idID" class="col-sm-2 col-form-label">Steam ID</label>--> | |||||
<div class="col"> | |||||
<input type="text" class="form-control" id="idID" placeholder="Steam ID" name="id"> | |||||
</div> | |||||
</div> | |||||
<div class="form-group row"> | |||||
<!--<label for="graphId" class="col-sm-2 col-form-label">Graph Type</label>--> | |||||
<div class="col"> | |||||
<select class="custom-select mb-3" id="graphId" name="graph"> | |||||
<option value="1">Friends of Friends Graph</option> | |||||
<option value="2">Common Friends Graph</option> | |||||
</select> | |||||
</div> | |||||
</div> | |||||
<div class="form-group row w-100"> | |||||
<div class="col text-center"> | |||||
<button type="submit" class="btn btn-light btn-lg">Generate Steam Graph</button> | |||||
</div> | |||||
</div> | |||||
</form> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<br> | |||||
</div> | |||||
<!- | |||||
┈┈╱▔▔▔▔▔╲┈┈┈HM┈HM | |||||
┈╱┈┈╱▔╲╲╲▏┈┈┈HMMM | |||||
╱┈┈╱━╱▔▔▔▔▔╲━╮┈┈ | |||||
▏┈▕┃▕╱▔╲╱▔╲▕╮┃┈┈ | |||||
▏┈▕╰━▏▊▕▕▋▕▕━╯┈┈ | |||||
╲┈┈╲╱▔╭╮▔▔┳╲╲┈┈┈ | |||||
┈╲┈┈▏╭━━━━╯▕▕┈┈┈ | |||||
┈┈╲┈╲▂▂▂▂▂▂╱╱┈┈┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊┈┈┈╲┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊▕╲┈┈╲ | |||||
┈╱▔╲▏┊┈┈┈┈┊▕╱▔╲▕ | |||||
┈▏ ┈┈┈╰┈┈┈┈╯┈┈┈▕▕ | |||||
┈╲┈┈┈╲┈┈┈┈╱┈┈┈╱┈╲ | |||||
┈┈╲┈┈▕▔▔▔▔▏┈┈╱╲╲╲▏ | |||||
┈╱▔┈┈▕┈┈┈┈▏┈┈▔╲▔▔ | |||||
┈╲▂▂▂╱┈┈┈┈╲▂▂▂╱┈ | |||||
If you are seeing this monkey that means that you are interested in my | |||||
code. Yay!! If you are not here to hack me ... you should really consider | |||||
contributing to some of my public projects on github. | |||||
https://github.com/jrtechs | |||||
--> | |||||
<!-- Footer --> | |||||
<footer class="text-center"> | |||||
<div class="footer-above"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Location</h3> | |||||
<p>Rochester Institute of Technology | |||||
<br>1 Lomb Memorial Dr, Rochester, NY 14623</p> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Around the Web</h3> | |||||
<ul class="list-inline"> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://www.youtube.com/c/JrtechsNet"> | |||||
<i class="fa fa-fw fa-youtube"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://github.com/jrtechs"> | |||||
<i class="fa fa-fw fa-github"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="http://jrtechs.net"> | |||||
<i class="fa fa-fw fa-wordpress"></i> | |||||
</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>About This Website</h3> | |||||
<p>Check out the source code for this website on my | |||||
<a href="https://github.com/jrtechs">github</a>.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="footer-below"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="col-lg-12"> | |||||
<p class="m-0 text-center text-white"><a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank">CC-BY-SA 4.0</a> <script type="text/javascript"> | |||||
document.write(new Date().getFullYear()); | |||||
</script> Jrtechs</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</footer> | |||||
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> | |||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> | |||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> | |||||
</body> | |||||
</html> |
@ -0,0 +1,249 @@ | |||||
<!DOCTYPE html> | |||||
<html lang="en"> | |||||
<head> | |||||
<meta charset="utf-8"> | |||||
<title>Jrtechs Steam Friend Graph Project</title> | |||||
<meta name="viewport" content="width=device-width, initial-scale=1"> | |||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |||||
<link rel="stylesheet" href="css/bootstrap.css" media="screen"> | |||||
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> | |||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" > </script> | |||||
</head> | |||||
<body> | |||||
<div class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"> | |||||
<div class="container"> | |||||
<a class="navbar-brand" href="#">Steam Graph Project</a> | |||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> | |||||
<span class="navbar-toggler-icon"></span> | |||||
</button> | |||||
<div class="collapse navbar-collapse" id="navbarSupportedContent"> | |||||
<ul class="navbar-nav mr-auto"> | |||||
<li class="nav-item active"> | |||||
<a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a> | |||||
</li> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="graphs.html">Graphs</a> | |||||
</li> | |||||
<!--<li class="nav-item">--> | |||||
<!--<a class="nav-link" href="profile.html">Profile Look-Up</a>--> | |||||
<!--</li>--> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="faq.html">FAQ</a> | |||||
</li> | |||||
</ul> | |||||
<ul class="nav navbar-nav navbar-right"> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.net">Blog</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.me">Resume</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://github.com/jrtechs">Github</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="container"> | |||||
<br><br><br> | |||||
<div id="carouselDiv" class="carousel slide" data-ride="carousel"> | |||||
<ol class="carousel-indicators"> | |||||
<li data-target="#carouselDiv" data-slide-to="0" class="active"></li> | |||||
<li data-target="#carouselDiv" data-slide-to="1"></li> | |||||
<li data-target="#carouselDiv" data-slide-to="2"></li> | |||||
<li data-target="#carouselDiv" data-slide-to="3"></li> | |||||
<li data-target="#carouselDiv" data-slide-to="4"></li> | |||||
<li data-target="#carouselDiv" data-slide-to="5"></li> | |||||
</ol> | |||||
<div class="carousel-inner"> | |||||
<div class="carousel-item active"> | |||||
<img class="d-block w-100" src="img/slider/img1.png" alt="First slide"> | |||||
</div> | |||||
<div class="carousel-item"> | |||||
<img class="d-block w-100" src="img/slider/img2.png" alt="Second slide"> | |||||
</div> | |||||
<div class="carousel-item"> | |||||
<img class="d-block w-100" src="img/slider/img3.png" alt="Third slide"> | |||||
</div> | |||||
<div class="carousel-item"> | |||||
<img class="d-block w-100" src="img/slider/img4.png" alt="Forth slide"> | |||||
</div> | |||||
<div class="carousel-item"> | |||||
<img class="d-block w-100" src="img/slider/img5.png" alt="Fifth slide"> | |||||
</div> | |||||
<div class="carousel-item"> | |||||
<img class="d-block w-100" src="img/slider/img6.png" alt="Sixth slide"> | |||||
</div> | |||||
</div> | |||||
<a class="carousel-control-prev" href="#carouselDiv" role="button" data-slide="prev"> | |||||
<span class="carousel-control-prev-icon" aria-hidden="true"></span> | |||||
<span class="sr-only">Previous</span> | |||||
</a> | |||||
<a class="carousel-control-next" href="#carouselDiv" role="button" data-slide="next"> | |||||
<span class="carousel-control-next-icon" aria-hidden="true"></span> | |||||
<span class="sr-only">Next</span> | |||||
</a> | |||||
</div> | |||||
<div class="row text-center"> | |||||
<div class="col text-center"><h1>Steam Graph Analysis</h1></div> | |||||
</div> | |||||
<div class="row"> | |||||
<div class="col-md-4"> | |||||
<p>This is a project that I threw together during a weekend to play around with | |||||
graph databases. This project uses the steam api to acquire people's friends lists; | |||||
this information is stored locally in a gremlin database. The client is sent information to | |||||
render on their javascript graph as it is pulled from the graph database via a web socket. | |||||
</p> | |||||
<center> | |||||
<h3>Try it out!</h3> | |||||
<a href="graphs.html" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Make a Graph</a> | |||||
</center> | |||||
</div> | |||||
<div class="col-md-8"> | |||||
<img src="Diagram.svg" alt="Diagram" width="100%" /> | |||||
</div> | |||||
</div> | |||||
<div class="d-flex justify-content-center"> | |||||
<p><iframe width="560" height="315" src="https://www.youtube.com/embed/DoDaHmyIPvQ" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p> | |||||
</div> | |||||
<div class="row"> | |||||
<div class="col-m-6"> | |||||
<h1 id="todo">Future Additions</h1> | |||||
<ul> | |||||
<li>Include a steam name to steam id lookup</li> | |||||
<li>Dockerize this entire environment</li> | |||||
<li>Connect the gremlin/janus server to a HBase server for persistent storage</li> | |||||
<li>Get the java web socket to work with ssh -- currently does not work with wss</li> | |||||
<li>Make more graphs to provide more insights | |||||
<ul> | |||||
<li>Most common friends of friends -- will show you people you may know</li> | |||||
<li>Graph of a larger chunk of the steam community</li> | |||||
<li>Graphs based on common games</li> | |||||
<li>...</li> | |||||
</ul> | |||||
</li> | |||||
<li>Write more documentation on how the system as a whole works.</li> | |||||
</ul> | |||||
<p>If you are interested in this project, or want to help work on it, check it out | |||||
on <a href="https://github.com/jrtechs/SteamFriendsGraph">github</a>.</p> | |||||
</div> | |||||
<div class="col-m-6 w-50" id="repo1"> | |||||
<script src="src/RepoJS/repo.js"></script> | |||||
<script> | |||||
$('#repo1').repo({ user: 'jrtechs', name: 'SteamFriendsGraph' }); | |||||
</script> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<!- | |||||
┈┈╱▔▔▔▔▔╲┈┈┈HM┈HM | |||||
┈╱┈┈╱▔╲╲╲▏┈┈┈HMMM | |||||
╱┈┈╱━╱▔▔▔▔▔╲━╮┈┈ | |||||
▏┈▕┃▕╱▔╲╱▔╲▕╮┃┈┈ | |||||
▏┈▕╰━▏▊▕▕▋▕▕━╯┈┈ | |||||
╲┈┈╲╱▔╭╮▔▔┳╲╲┈┈┈ | |||||
┈╲┈┈▏╭━━━━╯▕▕┈┈┈ | |||||
┈┈╲┈╲▂▂▂▂▂▂╱╱┈┈┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊┈┈┈╲┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊▕╲┈┈╲ | |||||
┈╱▔╲▏┊┈┈┈┈┊▕╱▔╲▕ | |||||
┈▏ ┈┈┈╰┈┈┈┈╯┈┈┈▕▕ | |||||
┈╲┈┈┈╲┈┈┈┈╱┈┈┈╱┈╲ | |||||
┈┈╲┈┈▕▔▔▔▔▏┈┈╱╲╲╲▏ | |||||
┈╱▔┈┈▕┈┈┈┈▏┈┈▔╲▔▔ | |||||
┈╲▂▂▂╱┈┈┈┈╲▂▂▂╱┈ | |||||
If you are seeing this monkey that means that you are interested in my | |||||
code. Yay!! If you are not here to hack me ... you should really consider | |||||
contributing to some of my public projects on github. | |||||
https://github.com/jrtechs | |||||
--> | |||||
<!-- Footer --> | |||||
<footer class="text-center"> | |||||
<div class="footer-above"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Location</h3> | |||||
<p>Rochester Institute of Technology | |||||
<br>1 Lomb Memorial Dr, Rochester, NY 14623</p> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Around the Web</h3> | |||||
<ul class="list-inline"> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://www.youtube.com/c/JrtechsNet"> | |||||
<i class="fa fa-fw fa-youtube"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://github.com/jrtechs"> | |||||
<i class="fa fa-fw fa-github"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="http://jrtechs.net"> | |||||
<i class="fa fa-fw fa-wordpress"></i> | |||||
</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>About This Website</h3> | |||||
<p>Check out the source code for this website on my | |||||
<a href="https://github.com/jrtechs">github</a>.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="footer-below"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="col-lg-12"> | |||||
<p class="m-0 text-center text-white"><a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank">CC-BY-SA 4.0</a> <script type="text/javascript"> | |||||
document.write(new Date().getFullYear()); | |||||
</script> Jrtechs</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</footer> | |||||
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> | |||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> | |||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> | |||||
</body> | |||||
</html> |
@ -0,0 +1,139 @@ | |||||
<!DOCTYPE html> | |||||
<html lang="en"> | |||||
<head> | |||||
<meta charset="utf-8"> | |||||
<title>Jrtechs Steam Friend Graph Project</title> | |||||
<meta name="viewport" content="width=device-width, initial-scale=1"> | |||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |||||
<link rel="stylesheet" href="css/bootstrap.css" media="screen"> | |||||
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> | |||||
</head> | |||||
<body> | |||||
<div class="navbar navbar-expand-lg fixed-top navbar-dark bg-primary"> | |||||
<div class="container"> | |||||
<a class="navbar-brand" href="#">Steam Graph Project</a> | |||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> | |||||
<span class="navbar-toggler-icon"></span> | |||||
</button> | |||||
<div class="collapse navbar-collapse" id="navbarSupportedContent"> | |||||
<ul class="navbar-nav mr-auto"> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="index.html">Home</a> | |||||
</li> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="graphs.html">Graphs<span class="sr-only">(current)</span></a> | |||||
</li> | |||||
<li class="nav-item active"> | |||||
<a class="nav-link" href="profile.html">Profile Look-Up</a> | |||||
</li> | |||||
<li class="nav-item"> | |||||
<a class="nav-link" href="faq.html">FAQ</a> | |||||
</li> | |||||
</ul> | |||||
<ul class="nav navbar-nav navbar-right"> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.net">Blog</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://jrtechs.me">Resume</a> | |||||
</li> | |||||
<li> | |||||
<a class="nav-link" href="https://github.com/jrtechs">Github</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="container"> | |||||
<br> | |||||
TDLTR | |||||
</div> | |||||
<!- | |||||
┈┈╱▔▔▔▔▔╲┈┈┈HM┈HM | |||||
┈╱┈┈╱▔╲╲╲▏┈┈┈HMMM | |||||
╱┈┈╱━╱▔▔▔▔▔╲━╮┈┈ | |||||
▏┈▕┃▕╱▔╲╱▔╲▕╮┃┈┈ | |||||
▏┈▕╰━▏▊▕▕▋▕▕━╯┈┈ | |||||
╲┈┈╲╱▔╭╮▔▔┳╲╲┈┈┈ | |||||
┈╲┈┈▏╭━━━━╯▕▕┈┈┈ | |||||
┈┈╲┈╲▂▂▂▂▂▂╱╱┈┈┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊┈┈┈╲┈ | |||||
┈┈┈┈▏┊┈┈┈┈┊▕╲┈┈╲ | |||||
┈╱▔╲▏┊┈┈┈┈┊▕╱▔╲▕ | |||||
┈▏ ┈┈┈╰┈┈┈┈╯┈┈┈▕▕ | |||||
┈╲┈┈┈╲┈┈┈┈╱┈┈┈╱┈╲ | |||||
┈┈╲┈┈▕▔▔▔▔▏┈┈╱╲╲╲▏ | |||||
┈╱▔┈┈▕┈┈┈┈▏┈┈▔╲▔▔ | |||||
┈╲▂▂▂╱┈┈┈┈╲▂▂▂╱┈ | |||||
If you are seeing this monkey that means that you are interested in my | |||||
code. Yay!! If you are not here to hack me ... you should really consider | |||||
contributing to some of my public projects on github. | |||||
https://github.com/jrtechs | |||||
--> | |||||
<!-- Footer --> | |||||
<footer class="text-center"> | |||||
<div class="footer-above"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Location</h3> | |||||
<p>Rochester Institute of Technology | |||||
<br>1 Lomb Memorial Dr, Rochester, NY 14623</p> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>Around the Web</h3> | |||||
<ul class="list-inline"> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://www.youtube.com/c/JrtechsNet"> | |||||
<i class="fa fa-fw fa-youtube"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="https://github.com/jrtechs"> | |||||
<i class="fa fa-fw fa-github"></i> | |||||
</a> | |||||
</li> | |||||
<li class="list-inline-item"> | |||||
<a class="btn-social btn-outline" href="http://jrtechs.net"> | |||||
<i class="fa fa-fw fa-wordpress"></i> | |||||
</a> | |||||
</li> | |||||
</ul> | |||||
</div> | |||||
<div class="footer-col col-md-4"> | |||||
<h3>About This Website</h3> | |||||
<p>Check out the source code for this website on my | |||||
<a href="https://github.com/jrtechs">github</a>.</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
<div class="footer-below"> | |||||
<div class="container"> | |||||
<div class="row"> | |||||
<div class="col-lg-12"> | |||||
<p class="m-0 text-center text-white"><a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank">CC-BY-SA 4.0</a> <script type="text/javascript"> | |||||
document.write(new Date().getFullYear()); | |||||
</script> Jrtechs</p> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</div> | |||||
</footer> | |||||
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> | |||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> | |||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script> | |||||
</body> | |||||
</html> |
@ -0,0 +1,37 @@ | |||||
Repo.js | |||||
======= | |||||
[![Build Status](http://img.shields.io/travis/darcyclarke/Repo.js.svg?style=flat-square)](https://travis-ci.org/darcyclarke/Repo.js) | |||||
[![Dependency Status](https://david-dm.org/darcyclarke/repo.js/badges.svg?style=flat-square)](https://david-dm.org/darcyclarke/repo.js/badges) | |||||
[![devDependency Status](https://david-dm.org/darcyclarke/repo.js/badges/dev-status.svg?style=flat-square)](https://david-dm.org/darcyclarke/repo.js/badges#info=devDependencies) | |||||
[![Code Climate](http://img.shields.io/codeclimate/github/darcyclarke/Repo.js.svg?style=flat-square)](https://codeclimate.com/github/darcyclarke/Repo.js) | |||||
[![npm](https://img.shields.io/npm/v/repo.js.svg?maxAge=2592000&style=flat-square)](https://www.npmjs.com/package/repo.js) | |||||
[![npm](https://img.shields.io/npm/dt/repo.js.svg?maxAge=2592000&style=flat-square)](https://www.npmjs.com/package/repo.js) | |||||
[![License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](http://darcyclarke.mit-license.org) | |||||
[![Join the chat at https://gitter.im/darcyclarke/Repo.js](http://img.shields.io/:Gitter-Join Chat-orange.svg?style=flat-square)](https://gitter.im/darcyclarke/Repo.js) | |||||
Repo.js is a jQuery plugin that lets you easily embed a Github repo onto your site. This is great for other plugin or library authors that want to showcase the contents of a repo on their project pages. | |||||
Repo.js uses [Markus Ekwall](https://twitter.com/#!/mekwall)'s [jQuery Vangogh](https://github.com/mekwall/jquery-vangogh) plugin for styling of file contents. Vangogh, subsequently, utilizes [highlight.js](https://github.com/isagalaev/highlight.js), written by [Ivan Sagalaev](https://github.com/isagalaev) for syntax highlighting. | |||||
##Example Usage | |||||
```javascript | |||||
$('body').repo({ user: 'darcyclarke', name: 'Repo.js' }); | |||||
```` | |||||
You can also reference a specific branch if you want: | |||||
```javascript | |||||
$('body').repo({ user: 'jquery', name: 'jquery', branch: 'strip_iife' }); | |||||
```` | |||||
##License | |||||
Copyright (c) 2016 Darcy Clarke <darcy@darcyclarke.me> | |||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
@ -0,0 +1,5 @@ | |||||
{ | |||||
"name": "Repo.js", | |||||
"version": "1.0", | |||||
"main": "repo.js" | |||||
} |
@ -0,0 +1,18 @@ | |||||
<?xml version="1.0" standalone="no"?> | |||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" > | |||||
<svg xmlns="http://www.w3.org/2000/svg"> | |||||
<metadata> | |||||
This is a custom SVG font generated by IcoMoon. | |||||
<iconset grid="16"></iconset> | |||||
</metadata> | |||||
<defs> | |||||
<font id="icomoon" horiz-adv-x="512" > | |||||
<font-face units-per-em="512" ascent="480" descent="-32" /> | |||||
<missing-glyph horiz-adv-x="512" /> | |||||
<glyph unicode="f" d="M 416.00,0.00L 512.00,256.00L 96.00,256.00L0.00,0.00 zM 64.00,288.00 L 0.00,0.00 L 0.00,416.00 L 144.00,416.00 L 208.00,352.00 L 416.00,352.00 L 416.00,288.00 Z" /> | |||||
<glyph unicode="t" d="M 451.716,380.285l-71.432,71.431C 364.728,467.272, 334.00,480.00, 312.00,480.00L 72.00,480.00 C 50.00,480.00, 32.00,462.00, 32.00,440.00l0.00-432.00 c0.00-22.00, 18.00-40.00, 40.00-40.00l 368.00,0.00 c 22.00,0.00, 40.00,18.00, 40.00,40.00 | |||||
L 480.00,312.00 C 480.00,334.00, 467.272,364.729, 451.716,380.285z M 429.089,357.657c 1.565-1.565, 3.125-3.487, 4.64-5.657L 352.00,352.00 L 352.00,433.728 | |||||
c 2.17-1.515, 4.092-3.075, 5.657-4.64L 429.089,357.657z M 448.00,8.00c0.00-4.336-3.664-8.00-8.00-8.00L 72.00,0.00 c-4.336,0.00-8.00,3.664-8.00,8.00L 64.00,440.00 c0.00,4.336, 3.664,8.00, 8.00,8.00 | |||||
l 240.00,0.00 c 2.416,0.00, 5.127-0.305, 8.00-0.852L 320.00,320.00 l 127.148,0.00 c 0.547-2.873, 0.852-5.583, 0.852-8.00L 448.00,8.00 z" /> | |||||
<glyph class="hidden" unicode="" d="M0,480L 512 -32L0 -32 z" horiz-adv-x="0" /> | |||||
</font></defs></svg> |
@ -0,0 +1,349 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.captors'); | |||||
/** | |||||
* The user inputs default captor. It deals with mouse events, keyboards | |||||
* events and touch events. | |||||
* | |||||
* @param {DOMElement} target The DOM element where the listeners will be | |||||
* bound. | |||||
* @param {camera} camera The camera related to the target. | |||||
* @param {configurable} settings The settings function. | |||||
* @return {sigma.captor} The fresh new captor instance. | |||||
*/ | |||||
sigma.captors.mouse = function(target, camera, settings) { | |||||
var _self = this, | |||||
_target = target, | |||||
_camera = camera, | |||||
_settings = settings, | |||||
// CAMERA MANAGEMENT: | |||||
// ****************** | |||||
// The camera position when the user starts dragging: | |||||
_startCameraX, | |||||
_startCameraY, | |||||
_startCameraAngle, | |||||
// The latest stage position: | |||||
_lastCameraX, | |||||
_lastCameraY, | |||||
_lastCameraAngle, | |||||
_lastCameraRatio, | |||||
// MOUSE MANAGEMENT: | |||||
// ***************** | |||||
// The mouse position when the user starts dragging: | |||||
_startMouseX, | |||||
_startMouseY, | |||||
_isMouseDown, | |||||
_isMoving, | |||||
_hasDragged, | |||||
_downStartTime, | |||||
_movingTimeoutId; | |||||
sigma.classes.dispatcher.extend(this); | |||||
sigma.utils.doubleClick(_target, 'click', _doubleClickHandler); | |||||
_target.addEventListener('DOMMouseScroll', _wheelHandler, false); | |||||
_target.addEventListener('mousewheel', _wheelHandler, false); | |||||
_target.addEventListener('mousemove', _moveHandler, false); | |||||
_target.addEventListener('mousedown', _downHandler, false); | |||||
_target.addEventListener('click', _clickHandler, false); | |||||
_target.addEventListener('mouseout', _outHandler, false); | |||||
document.addEventListener('mouseup', _upHandler, false); | |||||
/** | |||||
* This method unbinds every handlers that makes the captor work. | |||||
*/ | |||||
this.kill = function() { | |||||
sigma.utils.unbindDoubleClick(_target, 'click'); | |||||
_target.removeEventListener('DOMMouseScroll', _wheelHandler); | |||||
_target.removeEventListener('mousewheel', _wheelHandler); | |||||
_target.removeEventListener('mousemove', _moveHandler); | |||||
_target.removeEventListener('mousedown', _downHandler); | |||||
_target.removeEventListener('click', _clickHandler); | |||||
_target.removeEventListener('mouseout', _outHandler); | |||||
document.removeEventListener('mouseup', _upHandler); | |||||
}; | |||||
// MOUSE EVENTS: | |||||
// ************* | |||||
/** | |||||
* The handler listening to the 'move' mouse event. It will effectively | |||||
* drag the graph. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _moveHandler(e) { | |||||
var x, | |||||
y, | |||||
pos; | |||||
// Dispatch event: | |||||
if (_settings('mouseEnabled')) { | |||||
_self.dispatchEvent('mousemove', | |||||
sigma.utils.mouseCoords(e)); | |||||
if (_isMouseDown) { | |||||
_isMoving = true; | |||||
_hasDragged = true; | |||||
if (_movingTimeoutId) | |||||
clearTimeout(_movingTimeoutId); | |||||
_movingTimeoutId = setTimeout(function() { | |||||
_isMoving = false; | |||||
}, _settings('dragTimeout')); | |||||
sigma.misc.animation.killAll(_camera); | |||||
_camera.isMoving = true; | |||||
pos = _camera.cameraPosition( | |||||
sigma.utils.getX(e) - _startMouseX, | |||||
sigma.utils.getY(e) - _startMouseY, | |||||
true | |||||
); | |||||
x = _startCameraX - pos.x; | |||||
y = _startCameraY - pos.y; | |||||
if (x !== _camera.x || y !== _camera.y) { | |||||
_lastCameraX = _camera.x; | |||||
_lastCameraY = _camera.y; | |||||
_camera.goTo({ | |||||
x: x, | |||||
y: y | |||||
}); | |||||
} | |||||
if (e.preventDefault) | |||||
e.preventDefault(); | |||||
else | |||||
e.returnValue = false; | |||||
e.stopPropagation(); | |||||
return false; | |||||
} | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the 'up' mouse event. It will stop dragging the | |||||
* graph. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _upHandler(e) { | |||||
if (_settings('mouseEnabled') && _isMouseDown) { | |||||
_isMouseDown = false; | |||||
if (_movingTimeoutId) | |||||
clearTimeout(_movingTimeoutId); | |||||
_camera.isMoving = false; | |||||
var x = sigma.utils.getX(e), | |||||
y = sigma.utils.getY(e); | |||||
if (_isMoving) { | |||||
sigma.misc.animation.killAll(_camera); | |||||
sigma.misc.animation.camera( | |||||
_camera, | |||||
{ | |||||
x: _camera.x + | |||||
_settings('mouseInertiaRatio') * (_camera.x - _lastCameraX), | |||||
y: _camera.y + | |||||
_settings('mouseInertiaRatio') * (_camera.y - _lastCameraY) | |||||
}, | |||||
{ | |||||
easing: 'quadraticOut', | |||||
duration: _settings('mouseInertiaDuration') | |||||
} | |||||
); | |||||
} else if ( | |||||
_startMouseX !== x || | |||||
_startMouseY !== y | |||||
) | |||||
_camera.goTo({ | |||||
x: _camera.x, | |||||
y: _camera.y | |||||
}); | |||||
_self.dispatchEvent('mouseup', | |||||
sigma.utils.mouseCoords(e)); | |||||
// Update _isMoving flag: | |||||
_isMoving = false; | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the 'down' mouse event. It will start observing | |||||
* the mouse position for dragging the graph. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _downHandler(e) { | |||||
if (_settings('mouseEnabled')) { | |||||
_startCameraX = _camera.x; | |||||
_startCameraY = _camera.y; | |||||
_lastCameraX = _camera.x; | |||||
_lastCameraY = _camera.y; | |||||
_startMouseX = sigma.utils.getX(e); | |||||
_startMouseY = sigma.utils.getY(e); | |||||
_hasDragged = false; | |||||
_downStartTime = (new Date()).getTime(); | |||||
switch (e.which) { | |||||
case 2: | |||||
// Middle mouse button pressed | |||||
// Do nothing. | |||||
break; | |||||
case 3: | |||||
// Right mouse button pressed | |||||
_self.dispatchEvent('rightclick', | |||||
sigma.utils.mouseCoords(e, _startMouseX, _startMouseY)); | |||||
break; | |||||
// case 1: | |||||
default: | |||||
// Left mouse button pressed | |||||
_isMouseDown = true; | |||||
_self.dispatchEvent('mousedown', | |||||
sigma.utils.mouseCoords(e, _startMouseX, _startMouseY)); | |||||
} | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the 'out' mouse event. It will just redispatch | |||||
* the event. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _outHandler(e) { | |||||
if (_settings('mouseEnabled')) | |||||
_self.dispatchEvent('mouseout'); | |||||
} | |||||
/** | |||||
* The handler listening to the 'click' mouse event. It will redispatch the | |||||
* click event, but with normalized X and Y coordinates. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _clickHandler(e) { | |||||
if (_settings('mouseEnabled')) { | |||||
var event = sigma.utils.mouseCoords(e); | |||||
event.isDragging = | |||||
(((new Date()).getTime() - _downStartTime) > 100) && _hasDragged; | |||||
_self.dispatchEvent('click', event); | |||||
} | |||||
if (e.preventDefault) | |||||
e.preventDefault(); | |||||
else | |||||
e.returnValue = false; | |||||
e.stopPropagation(); | |||||
return false; | |||||
} | |||||
/** | |||||
* The handler listening to the double click custom event. It will | |||||
* basically zoom into the graph. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _doubleClickHandler(e) { | |||||
var pos, | |||||
ratio, | |||||
animation; | |||||
if (_settings('mouseEnabled')) { | |||||
ratio = 1 / _settings('doubleClickZoomingRatio'); | |||||
_self.dispatchEvent('doubleclick', | |||||
sigma.utils.mouseCoords(e, _startMouseX, _startMouseY)); | |||||
if (_settings('doubleClickEnabled')) { | |||||
pos = _camera.cameraPosition( | |||||
sigma.utils.getX(e) - sigma.utils.getCenter(e).x, | |||||
sigma.utils.getY(e) - sigma.utils.getCenter(e).y, | |||||
true | |||||
); | |||||
animation = { | |||||
duration: _settings('doubleClickZoomDuration') | |||||
}; | |||||
sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); | |||||
} | |||||
if (e.preventDefault) | |||||
e.preventDefault(); | |||||
else | |||||
e.returnValue = false; | |||||
e.stopPropagation(); | |||||
return false; | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the 'wheel' mouse event. It will basically zoom | |||||
* in or not into the graph. | |||||
* | |||||
* @param {event} e A mouse event. | |||||
*/ | |||||
function _wheelHandler(e) { | |||||
var pos, | |||||
ratio, | |||||
animation, | |||||
wheelDelta = sigma.utils.getDelta(e); | |||||
if (_settings('mouseEnabled') && _settings('mouseWheelEnabled') && wheelDelta !== 0) { | |||||
ratio = wheelDelta > 0 ? | |||||
1 / _settings('zoomingRatio') : | |||||
_settings('zoomingRatio'); | |||||
pos = _camera.cameraPosition( | |||||
sigma.utils.getX(e) - sigma.utils.getCenter(e).x, | |||||
sigma.utils.getY(e) - sigma.utils.getCenter(e).y, | |||||
true | |||||
); | |||||
animation = { | |||||
duration: _settings('mouseZoomDuration') | |||||
}; | |||||
sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); | |||||
if (e.preventDefault) | |||||
e.preventDefault(); | |||||
else | |||||
e.returnValue = false; | |||||
e.stopPropagation(); | |||||
return false; | |||||
} | |||||
} | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,410 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.captors'); | |||||
/** | |||||
* The user inputs default captor. It deals with mouse events, keyboards | |||||
* events and touch events. | |||||
* | |||||
* @param {DOMElement} target The DOM element where the listeners will be | |||||
* bound. | |||||
* @param {camera} camera The camera related to the target. | |||||
* @param {configurable} settings The settings function. | |||||
* @return {sigma.captor} The fresh new captor instance. | |||||
*/ | |||||
sigma.captors.touch = function(target, camera, settings) { | |||||
var _self = this, | |||||
_target = target, | |||||
_camera = camera, | |||||
_settings = settings, | |||||
// CAMERA MANAGEMENT: | |||||
// ****************** | |||||
// The camera position when the user starts dragging: | |||||
_startCameraX, | |||||
_startCameraY, | |||||
_startCameraAngle, | |||||
_startCameraRatio, | |||||
// The latest stage position: | |||||
_lastCameraX, | |||||
_lastCameraY, | |||||
_lastCameraAngle, | |||||
_lastCameraRatio, | |||||
// TOUCH MANAGEMENT: | |||||
// ***************** | |||||
// Touches that are down: | |||||
_downTouches = [], | |||||
_startTouchX0, | |||||
_startTouchY0, | |||||
_startTouchX1, | |||||
_startTouchY1, | |||||
_startTouchAngle, | |||||
_startTouchDistance, | |||||
_touchMode, | |||||
_isMoving, | |||||
_doubleTap, | |||||
_movingTimeoutId; | |||||
sigma.classes.dispatcher.extend(this); | |||||
sigma.utils.doubleClick(_target, 'touchstart', _doubleTapHandler); | |||||
_target.addEventListener('touchstart', _handleStart, false); | |||||
_target.addEventListener('touchend', _handleLeave, false); | |||||
_target.addEventListener('touchcancel', _handleLeave, false); | |||||
_target.addEventListener('touchleave', _handleLeave, false); | |||||
_target.addEventListener('touchmove', _handleMove, false); | |||||
function position(e) { | |||||
var offset = sigma.utils.getOffset(_target); | |||||
return { | |||||
x: e.pageX - offset.left, | |||||
y: e.pageY - offset.top | |||||
}; | |||||
} | |||||
/** | |||||
* This method unbinds every handlers that makes the captor work. | |||||
*/ | |||||
this.kill = function() { | |||||
sigma.utils.unbindDoubleClick(_target, 'touchstart'); | |||||
_target.addEventListener('touchstart', _handleStart); | |||||
_target.addEventListener('touchend', _handleLeave); | |||||
_target.addEventListener('touchcancel', _handleLeave); | |||||
_target.addEventListener('touchleave', _handleLeave); | |||||
_target.addEventListener('touchmove', _handleMove); | |||||
}; | |||||
// TOUCH EVENTS: | |||||
// ************* | |||||
/** | |||||
* The handler listening to the 'touchstart' event. It will set the touch | |||||
* mode ("_touchMode") and start observing the user touch moves. | |||||
* | |||||
* @param {event} e A touch event. | |||||
*/ | |||||
function _handleStart(e) { | |||||
if (_settings('touchEnabled')) { | |||||
var x0, | |||||
x1, | |||||
y0, | |||||
y1, | |||||
pos0, | |||||
pos1; | |||||
_downTouches = e.touches; | |||||
switch (_downTouches.length) { | |||||
case 1: | |||||
_camera.isMoving = true; | |||||
_touchMode = 1; | |||||
_startCameraX = _camera.x; | |||||
_startCameraY = _camera.y; | |||||
_lastCameraX = _camera.x; | |||||
_lastCameraY = _camera.y; | |||||
pos0 = position(_downTouches[0]); | |||||
_startTouchX0 = pos0.x; | |||||
_startTouchY0 = pos0.y; | |||||
break; | |||||
case 2: | |||||
_camera.isMoving = true; | |||||
_touchMode = 2; | |||||
pos0 = position(_downTouches[0]); | |||||
pos1 = position(_downTouches[1]); | |||||
x0 = pos0.x; | |||||
y0 = pos0.y; | |||||
x1 = pos1.x; | |||||
y1 = pos1.y; | |||||
_lastCameraX = _camera.x; | |||||
_lastCameraY = _camera.y; | |||||
_startCameraAngle = _camera.angle; | |||||
_startCameraRatio = _camera.ratio; | |||||
_startCameraX = _camera.x; | |||||
_startCameraY = _camera.y; | |||||
_startTouchX0 = x0; | |||||
_startTouchY0 = y0; | |||||
_startTouchX1 = x1; | |||||
_startTouchY1 = y1; | |||||
_startTouchAngle = Math.atan2( | |||||
_startTouchY1 - _startTouchY0, | |||||
_startTouchX1 - _startTouchX0 | |||||
); | |||||
_startTouchDistance = Math.sqrt( | |||||
(_startTouchY1 - _startTouchY0) * | |||||
(_startTouchY1 - _startTouchY0) + | |||||
(_startTouchX1 - _startTouchX0) * | |||||
(_startTouchX1 - _startTouchX0) | |||||
); | |||||
e.preventDefault(); | |||||
return false; | |||||
} | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the 'touchend', 'touchcancel' and 'touchleave' | |||||
* event. It will update the touch mode if there are still at least one | |||||
* finger, and stop dragging else. | |||||
* | |||||
* @param {event} e A touch event. | |||||
*/ | |||||
function _handleLeave(e) { | |||||
if (_settings('touchEnabled')) { | |||||
_downTouches = e.touches; | |||||
var inertiaRatio = _settings('touchInertiaRatio'); | |||||
if (_movingTimeoutId) { | |||||
_isMoving = false; | |||||
clearTimeout(_movingTimeoutId); | |||||
} | |||||
switch (_touchMode) { | |||||
case 2: | |||||
if (e.touches.length === 1) { | |||||
_handleStart(e); | |||||
e.preventDefault(); | |||||
break; | |||||
} | |||||
/* falls through */ | |||||
case 1: | |||||
_camera.isMoving = false; | |||||
_self.dispatchEvent('stopDrag'); | |||||
if (_isMoving) { | |||||
_doubleTap = false; | |||||
sigma.misc.animation.camera( | |||||
_camera, | |||||
{ | |||||
x: _camera.x + | |||||
inertiaRatio * (_camera.x - _lastCameraX), | |||||
y: _camera.y + | |||||
inertiaRatio * (_camera.y - _lastCameraY) | |||||
}, | |||||
{ | |||||
easing: 'quadraticOut', | |||||
duration: _settings('touchInertiaDuration') | |||||
} | |||||
); | |||||
} | |||||
_isMoving = false; | |||||
_touchMode = 0; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the 'touchmove' event. It will effectively drag | |||||
* the graph, and eventually zooms and turn it if the user is using two | |||||
* fingers. | |||||
* | |||||
* @param {event} e A touch event. | |||||
*/ | |||||
function _handleMove(e) { | |||||
if (!_doubleTap && _settings('touchEnabled')) { | |||||
var x0, | |||||
x1, | |||||
y0, | |||||
y1, | |||||
cos, | |||||
sin, | |||||
end, | |||||
pos0, | |||||
pos1, | |||||
diff, | |||||
start, | |||||
dAngle, | |||||
dRatio, | |||||
newStageX, | |||||
newStageY, | |||||
newStageRatio, | |||||
newStageAngle; | |||||
_downTouches = e.touches; | |||||
_isMoving = true; | |||||
if (_movingTimeoutId) | |||||
clearTimeout(_movingTimeoutId); | |||||
_movingTimeoutId = setTimeout(function() { | |||||
_isMoving = false; | |||||
}, _settings('dragTimeout')); | |||||
switch (_touchMode) { | |||||
case 1: | |||||
pos0 = position(_downTouches[0]); | |||||
x0 = pos0.x; | |||||
y0 = pos0.y; | |||||
diff = _camera.cameraPosition( | |||||
x0 - _startTouchX0, | |||||
y0 - _startTouchY0, | |||||
true | |||||
); | |||||
newStageX = _startCameraX - diff.x; | |||||
newStageY = _startCameraY - diff.y; | |||||
if (newStageX !== _camera.x || newStageY !== _camera.y) { | |||||
_lastCameraX = _camera.x; | |||||
_lastCameraY = _camera.y; | |||||
_camera.goTo({ | |||||
x: newStageX, | |||||
y: newStageY | |||||
}); | |||||
_self.dispatchEvent('mousemove', | |||||
sigma.utils.mouseCoords(e, pos0.x, pos0.y)); | |||||
_self.dispatchEvent('drag'); | |||||
} | |||||
break; | |||||
case 2: | |||||
pos0 = position(_downTouches[0]); | |||||
pos1 = position(_downTouches[1]); | |||||
x0 = pos0.x; | |||||
y0 = pos0.y; | |||||
x1 = pos1.x; | |||||
y1 = pos1.y; | |||||
start = _camera.cameraPosition( | |||||
(_startTouchX0 + _startTouchX1) / 2 - | |||||
sigma.utils.getCenter(e).x, | |||||
(_startTouchY0 + _startTouchY1) / 2 - | |||||
sigma.utils.getCenter(e).y, | |||||
true | |||||
); | |||||
end = _camera.cameraPosition( | |||||
(x0 + x1) / 2 - sigma.utils.getCenter(e).x, | |||||
(y0 + y1) / 2 - sigma.utils.getCenter(e).y, | |||||
true | |||||
); | |||||
dAngle = Math.atan2(y1 - y0, x1 - x0) - _startTouchAngle; | |||||
dRatio = Math.sqrt( | |||||
(y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0) | |||||
) / _startTouchDistance; | |||||
// Translation: | |||||
x0 = start.x; | |||||
y0 = start.y; | |||||
// Homothetic transformation: | |||||
newStageRatio = _startCameraRatio / dRatio; | |||||
x0 = x0 * dRatio; | |||||
y0 = y0 * dRatio; | |||||
// Rotation: | |||||
newStageAngle = _startCameraAngle - dAngle; | |||||
cos = Math.cos(-dAngle); | |||||
sin = Math.sin(-dAngle); | |||||
x1 = x0 * cos + y0 * sin; | |||||
y1 = y0 * cos - x0 * sin; | |||||
x0 = x1; | |||||
y0 = y1; | |||||
// Finalize: | |||||
newStageX = x0 - end.x + _startCameraX; | |||||
newStageY = y0 - end.y + _startCameraY; | |||||
if ( | |||||
newStageRatio !== _camera.ratio || | |||||
newStageAngle !== _camera.angle || | |||||
newStageX !== _camera.x || | |||||
newStageY !== _camera.y | |||||
) { | |||||
_lastCameraX = _camera.x; | |||||
_lastCameraY = _camera.y; | |||||
_lastCameraAngle = _camera.angle; | |||||
_lastCameraRatio = _camera.ratio; | |||||
_camera.goTo({ | |||||
x: newStageX, | |||||
y: newStageY, | |||||
angle: newStageAngle, | |||||
ratio: newStageRatio | |||||
}); | |||||
_self.dispatchEvent('drag'); | |||||
} | |||||
break; | |||||
} | |||||
e.preventDefault(); | |||||
return false; | |||||
} | |||||
} | |||||
/** | |||||
* The handler listening to the double tap custom event. It will | |||||
* basically zoom into the graph. | |||||
* | |||||
* @param {event} e A touch event. | |||||
*/ | |||||
function _doubleTapHandler(e) { | |||||
var pos, | |||||
ratio, | |||||
animation; | |||||
if (e.touches && e.touches.length === 1 && _settings('touchEnabled')) { | |||||
_doubleTap = true; | |||||
ratio = 1 / _settings('doubleClickZoomingRatio'); | |||||
pos = position(e.touches[0]); | |||||
_self.dispatchEvent('doubleclick', | |||||
sigma.utils.mouseCoords(e, pos.x, pos.y)); | |||||
if (_settings('doubleClickEnabled')) { | |||||
pos = _camera.cameraPosition( | |||||
pos.x - sigma.utils.getCenter(e).x, | |||||
pos.y - sigma.utils.getCenter(e).y, | |||||
true | |||||
); | |||||
animation = { | |||||
duration: _settings('doubleClickZoomDuration'), | |||||
onComplete: function() { | |||||
_doubleTap = false; | |||||
} | |||||
}; | |||||
sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); | |||||
} | |||||
if (e.preventDefault) | |||||
e.preventDefault(); | |||||
else | |||||
e.returnValue = false; | |||||
e.stopPropagation(); | |||||
return false; | |||||
} | |||||
} | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,240 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
sigma.utils.pkg('sigma.classes'); | |||||
/** | |||||
* The camera constructor. It just initializes its attributes and methods. | |||||
* | |||||
* @param {string} id The id. | |||||
* @param {sigma.classes.graph} graph The graph. | |||||
* @param {configurable} settings The settings function. | |||||
* @param {?object} options Eventually some overriding options. | |||||
* @return {camera} Returns the fresh new camera instance. | |||||
*/ | |||||
sigma.classes.camera = function(id, graph, settings, options) { | |||||
sigma.classes.dispatcher.extend(this); | |||||
Object.defineProperty(this, 'graph', { | |||||
value: graph | |||||
}); | |||||
Object.defineProperty(this, 'id', { | |||||
value: id | |||||
}); | |||||
Object.defineProperty(this, 'readPrefix', { | |||||
value: 'read_cam' + id + ':' | |||||
}); | |||||
Object.defineProperty(this, 'prefix', { | |||||
value: 'cam' + id + ':' | |||||
}); | |||||
this.x = 0; | |||||
this.y = 0; | |||||
this.ratio = 1; | |||||
this.angle = 0; | |||||
this.isAnimated = false; | |||||
this.settings = (typeof options === 'object' && options) ? | |||||
settings.embedObject(options) : | |||||
settings; | |||||
}; | |||||
/** | |||||
* Updates the camera position. | |||||
* | |||||
* @param {object} coordinates The new coordinates object. | |||||
* @return {camera} Returns the camera. | |||||
*/ | |||||
sigma.classes.camera.prototype.goTo = function(coordinates) { | |||||
if (!this.settings('enableCamera')) | |||||
return this; | |||||
var i, | |||||
l, | |||||
c = coordinates || {}, | |||||
keys = ['x', 'y', 'ratio', 'angle']; | |||||
for (i = 0, l = keys.length; i < l; i++) | |||||
if (c[keys[i]] !== undefined) { | |||||
if (typeof c[keys[i]] === 'number' && !isNaN(c[keys[i]])) | |||||
this[keys[i]] = c[keys[i]]; | |||||
else | |||||
throw 'Value for "' + keys[i] + '" is not a number.'; | |||||
} | |||||
this.dispatchEvent('coordinatesUpdated'); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method takes a graph and computes for each node and edges its | |||||
* coordinates relatively to the center of the camera. Basically, it will | |||||
* compute the coordinates that will be used by the graphic renderers. | |||||
* | |||||
* Since it should be possible to use different cameras and different | |||||
* renderers, it is possible to specify a prefix to put before the new | |||||
* coordinates (to get something like "node.camera1_x") | |||||
* | |||||
* @param {?string} read The prefix of the coordinates to read. | |||||
* @param {?string} write The prefix of the coordinates to write. | |||||
* @param {?object} options Eventually an object of options. Those can be: | |||||
* - A restricted nodes array. | |||||
* - A restricted edges array. | |||||
* - A width. | |||||
* - A height. | |||||
* @return {camera} Returns the camera. | |||||
*/ | |||||
sigma.classes.camera.prototype.applyView = function(read, write, options) { | |||||
options = options || {}; | |||||
write = write !== undefined ? write : this.prefix; | |||||
read = read !== undefined ? read : this.readPrefix; | |||||
var nodes = options.nodes || this.graph.nodes(), | |||||
edges = options.edges || this.graph.edges(); | |||||
var i, | |||||
l, | |||||
node, | |||||
relCos = Math.cos(this.angle) / this.ratio, | |||||
relSin = Math.sin(this.angle) / this.ratio, | |||||
nodeRatio = Math.pow(this.ratio, this.settings('nodesPowRatio')), | |||||
edgeRatio = Math.pow(this.ratio, this.settings('edgesPowRatio')), | |||||
xOffset = (options.width || 0) / 2 - this.x * relCos - this.y * relSin, | |||||
yOffset = (options.height || 0) / 2 - this.y * relCos + this.x * relSin; | |||||
for (i = 0, l = nodes.length; i < l; i++) { | |||||
node = nodes[i]; | |||||
node[write + 'x'] = | |||||
(node[read + 'x'] || 0) * relCos + | |||||
(node[read + 'y'] || 0) * relSin + | |||||
xOffset; | |||||
node[write + 'y'] = | |||||
(node[read + 'y'] || 0) * relCos - | |||||
(node[read + 'x'] || 0) * relSin + | |||||
yOffset; | |||||
node[write + 'size'] = | |||||
(node[read + 'size'] || 0) / | |||||
nodeRatio; | |||||
} | |||||
for (i = 0, l = edges.length; i < l; i++) { | |||||
edges[i][write + 'size'] = | |||||
(edges[i][read + 'size'] || 0) / | |||||
edgeRatio; | |||||
} | |||||
return this; | |||||
}; | |||||
/** | |||||
* This function converts the coordinates of a point from the frame of the | |||||
* camera to the frame of the graph. | |||||
* | |||||
* @param {number} x The X coordinate of the point in the frame of the | |||||
* camera. | |||||
* @param {number} y The Y coordinate of the point in the frame of the | |||||
* camera. | |||||
* @return {object} The point coordinates in the frame of the graph. | |||||
*/ | |||||
sigma.classes.camera.prototype.graphPosition = function(x, y, vector) { | |||||
var X = 0, | |||||
Y = 0, | |||||
cos = Math.cos(this.angle), | |||||
sin = Math.sin(this.angle); | |||||
// Revert the origin differential vector: | |||||
if (!vector) { | |||||
X = - (this.x * cos + this.y * sin) / this.ratio; | |||||
Y = - (this.y * cos - this.x * sin) / this.ratio; | |||||
} | |||||
return { | |||||
x: (x * cos + y * sin) / this.ratio + X, | |||||
y: (y * cos - x * sin) / this.ratio + Y | |||||
}; | |||||
}; | |||||
/** | |||||
* This function converts the coordinates of a point from the frame of the | |||||
* graph to the frame of the camera. | |||||
* | |||||
* @param {number} x The X coordinate of the point in the frame of the | |||||
* graph. | |||||
* @param {number} y The Y coordinate of the point in the frame of the | |||||
* graph. | |||||
* @return {object} The point coordinates in the frame of the camera. | |||||
*/ | |||||
sigma.classes.camera.prototype.cameraPosition = function(x, y, vector) { | |||||
var X = 0, | |||||
Y = 0, | |||||
cos = Math.cos(this.angle), | |||||
sin = Math.sin(this.angle); | |||||
// Revert the origin differential vector: | |||||
if (!vector) { | |||||
X = - (this.x * cos + this.y * sin) / this.ratio; | |||||
Y = - (this.y * cos - this.x * sin) / this.ratio; | |||||
} | |||||
return { | |||||
x: ((x - X) * cos - (y - Y) * sin) * this.ratio, | |||||
y: ((y - Y) * cos + (x - X) * sin) * this.ratio | |||||
}; | |||||
}; | |||||
/** | |||||
* This method returns the transformation matrix of the camera. This is | |||||
* especially useful to apply the camera view directly in shaders, in case of | |||||
* WebGL rendering. | |||||
* | |||||
* @return {array} The transformation matrix. | |||||
*/ | |||||
sigma.classes.camera.prototype.getMatrix = function() { | |||||
var scale = sigma.utils.matrices.scale(1 / this.ratio), | |||||
rotation = sigma.utils.matrices.rotation(this.angle), | |||||
translation = sigma.utils.matrices.translation(-this.x, -this.y), | |||||
matrix = sigma.utils.matrices.multiply( | |||||
translation, | |||||
sigma.utils.matrices.multiply( | |||||
rotation, | |||||
scale | |||||
) | |||||
); | |||||
return matrix; | |||||
}; | |||||
/** | |||||
* Taking a width and a height as parameters, this method returns the | |||||
* coordinates of the rectangle representing the camera on screen, in the | |||||
* graph's referentiel. | |||||
* | |||||
* To keep displaying labels of nodes going out of the screen, the method | |||||
* keeps a margin around the screen in the returned rectangle. | |||||
* | |||||
* @param {number} width The width of the screen. | |||||
* @param {number} height The height of the screen. | |||||
* @return {object} The rectangle as x1, y1, x2 and y2, representing | |||||
* two opposite points. | |||||
*/ | |||||
sigma.classes.camera.prototype.getRectangle = function(width, height) { | |||||
var widthVect = this.cameraPosition(width, 0, true), | |||||
heightVect = this.cameraPosition(0, height, true), | |||||
centerVect = this.cameraPosition(width / 2, height / 2, true), | |||||
marginX = this.cameraPosition(width / 4, 0, true).x, | |||||
marginY = this.cameraPosition(0, height / 4, true).y; | |||||
return { | |||||
x1: this.x - centerVect.x - marginX, | |||||
y1: this.y - centerVect.y - marginY, | |||||
x2: this.x - centerVect.x + marginX + widthVect.x, | |||||
y2: this.y - centerVect.y - marginY + widthVect.y, | |||||
height: Math.sqrt( | |||||
Math.pow(heightVect.x, 2) + | |||||
Math.pow(heightVect.y + 2 * marginY, 2) | |||||
) | |||||
}; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,116 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
/** | |||||
* This utils aims to facilitate the manipulation of each instance setting. | |||||
* Using a function instead of an object brings two main advantages: First, | |||||
* it will be easier in the future to catch settings updates through a | |||||
* function than an object. Second, giving it a full object will "merge" it | |||||
* to the settings object properly, keeping us to have to always add a loop. | |||||
* | |||||
* @return {configurable} The "settings" function. | |||||
*/ | |||||
var configurable = function() { | |||||
var i, | |||||
l, | |||||
data = {}, | |||||
datas = Array.prototype.slice.call(arguments, 0); | |||||
/** | |||||
* The method to use to set or get any property of this instance. | |||||
* | |||||
* @param {string|object} a1 If it is a string and if a2 is undefined, | |||||
* then it will return the corresponding | |||||
* property. If it is a string and if a2 is | |||||
* set, then it will set a2 as the property | |||||
* corresponding to a1, and return this. If | |||||
* it is an object, then each pair string + | |||||
* object(or any other type) will be set as a | |||||
* property. | |||||
* @param {*?} a2 The new property corresponding to a1 if a1 | |||||
* is a string. | |||||
* @return {*|configurable} Returns itself or the corresponding | |||||
* property. | |||||
* | |||||
* Polymorphism: | |||||
* ************* | |||||
* Here are some basic use examples: | |||||
* | |||||
* > settings = new configurable(); | |||||
* > settings('mySetting', 42); | |||||
* > settings('mySetting'); // Logs: 42 | |||||
* > settings('mySetting', 123); | |||||
* > settings('mySetting'); // Logs: 123 | |||||
* > settings({mySetting: 456}); | |||||
* > settings('mySetting'); // Logs: 456 | |||||
* | |||||
* Also, it is possible to use the function as a fallback: | |||||
* > settings({mySetting: 'abc'}, 'mySetting'); // Logs: 'abc' | |||||
* > settings({hisSetting: 'abc'}, 'mySetting'); // Logs: 456 | |||||
*/ | |||||
var settings = function(a1, a2) { | |||||
var o, | |||||
i, | |||||
l, | |||||
k; | |||||
if (arguments.length === 1 && typeof a1 === 'string') { | |||||
if (data[a1] !== undefined) | |||||
return data[a1]; | |||||
for (i = 0, l = datas.length; i < l; i++) | |||||
if (datas[i][a1] !== undefined) | |||||
return datas[i][a1]; | |||||
return undefined; | |||||
} else if (typeof a1 === 'object' && typeof a2 === 'string') { | |||||
return (a1 || {})[a2] !== undefined ? a1[a2] : settings(a2); | |||||
} else { | |||||
o = (typeof a1 === 'object' && a2 === undefined) ? a1 : {}; | |||||
if (typeof a1 === 'string') | |||||
o[a1] = a2; | |||||
for (i = 0, k = Object.keys(o), l = k.length; i < l; i++) | |||||
data[k[i]] = o[k[i]]; | |||||
return this; | |||||
} | |||||
}; | |||||
/** | |||||
* This method returns a new configurable function, with new objects | |||||
* | |||||
* @param {object*} Any number of objects to search in. | |||||
* @return {function} Returns the function. Check its documentation to know | |||||
* more about how it works. | |||||
*/ | |||||
settings.embedObjects = function() { | |||||
var args = datas.concat( | |||||
data | |||||
).concat( | |||||
Array.prototype.splice.call(arguments, 0) | |||||
); | |||||
return configurable.apply({}, args); | |||||
}; | |||||
// Initialize | |||||
for (i = 0, l = arguments.length; i < l; i++) | |||||
settings(arguments[i]); | |||||
return settings; | |||||
}; | |||||
/** | |||||
* EXPORT: | |||||
* ******* | |||||
*/ | |||||
if (typeof this.sigma !== 'undefined') { | |||||
this.sigma.classes = this.sigma.classes || {}; | |||||
this.sigma.classes.configurable = configurable; | |||||
} else if (typeof exports !== 'undefined') { | |||||
if (typeof module !== 'undefined' && module.exports) | |||||
exports = module.exports = configurable; | |||||
exports.configurable = configurable; | |||||
} else | |||||
this.configurable = configurable; | |||||
}).call(this); |
@ -0,0 +1,204 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
/** | |||||
* Dispatcher constructor. | |||||
* | |||||
* @return {dispatcher} The new dispatcher instance. | |||||
*/ | |||||
var dispatcher = function() { | |||||
Object.defineProperty(this, '_handlers', { | |||||
value: {} | |||||
}); | |||||
}; | |||||
/** | |||||
* Will execute the handler everytime that the indicated event (or the | |||||
* indicated events) will be triggered. | |||||
* | |||||
* @param {string} events The name of the event (or the events | |||||
* separated by spaces). | |||||
* @param {function(Object)} handler The handler to bind. | |||||
* @return {dispatcher} Returns the instance itself. | |||||
*/ | |||||
dispatcher.prototype.bind = function(events, handler) { | |||||
var i, | |||||
l, | |||||
event, | |||||
eArray; | |||||
if ( | |||||
arguments.length === 1 && | |||||
typeof arguments[0] === 'object' | |||||
) | |||||
for (events in arguments[0]) | |||||
this.bind(events, arguments[0][events]); | |||||
else if ( | |||||
arguments.length === 2 && | |||||
typeof arguments[1] === 'function' | |||||
) { | |||||
eArray = typeof events === 'string' ? events.split(' ') : events; | |||||
for (i = 0, l = eArray.length; i !== l; i += 1) { | |||||
event = eArray[i]; | |||||
// Check that event is not '': | |||||
if (!event) | |||||
continue; | |||||
if (!this._handlers[event]) | |||||
this._handlers[event] = []; | |||||
// Using an object instead of directly the handler will make possible | |||||
// later to add flags | |||||
this._handlers[event].push({ | |||||
handler: handler | |||||
}); | |||||
} | |||||
} else | |||||
throw 'bind: Wrong arguments.'; | |||||
return this; | |||||
}; | |||||
/** | |||||
* Removes the handler from a specified event (or specified events). | |||||
* | |||||
* @param {?string} events The name of the event (or the events | |||||
* separated by spaces). If undefined, | |||||
* then all handlers are removed. | |||||
* @param {?function(object)} handler The handler to unbind. If undefined, | |||||
* each handler bound to the event or the | |||||
* events will be removed. | |||||
* @return {dispatcher} Returns the instance itself. | |||||
*/ | |||||
dispatcher.prototype.unbind = function(events, handler) { | |||||
var i, | |||||
n, | |||||
j, | |||||
m, | |||||
k, | |||||
a, | |||||
event, | |||||
eArray = typeof events === 'string' ? events.split(' ') : events; | |||||
if (!arguments.length) { | |||||
for (k in this._handlers) | |||||
delete this._handlers[k]; | |||||
return this; | |||||
} | |||||
if (handler) { | |||||
for (i = 0, n = eArray.length; i !== n; i += 1) { | |||||
event = eArray[i]; | |||||
if (this._handlers[event]) { | |||||
a = []; | |||||
for (j = 0, m = this._handlers[event].length; j !== m; j += 1) | |||||
if (this._handlers[event][j].handler !== handler) | |||||
a.push(this._handlers[event][j]); | |||||
this._handlers[event] = a; | |||||
} | |||||
if (this._handlers[event] && this._handlers[event].length === 0) | |||||
delete this._handlers[event]; | |||||
} | |||||
} else | |||||
for (i = 0, n = eArray.length; i !== n; i += 1) | |||||
delete this._handlers[eArray[i]]; | |||||
return this; | |||||
}; | |||||
/** | |||||
* Executes each handler bound to the event | |||||
* | |||||
* @param {string} events The name of the event (or the events separated | |||||
* by spaces). | |||||
* @param {?object} data The content of the event (optional). | |||||
* @return {dispatcher} Returns the instance itself. | |||||
*/ | |||||
dispatcher.prototype.dispatchEvent = function(events, data) { | |||||
var i, | |||||
n, | |||||
j, | |||||
m, | |||||
a, | |||||
event, | |||||
eventName, | |||||
self = this, | |||||
eArray = typeof events === 'string' ? events.split(' ') : events; | |||||
data = data === undefined ? {} : data; | |||||
for (i = 0, n = eArray.length; i !== n; i += 1) { | |||||
eventName = eArray[i]; | |||||
if (this._handlers[eventName]) { | |||||
event = self.getEvent(eventName, data); | |||||
a = []; | |||||
for (j = 0, m = this._handlers[eventName].length; j !== m; j += 1) { | |||||
this._handlers[eventName][j].handler(event); | |||||
if (!this._handlers[eventName][j].one) | |||||
a.push(this._handlers[eventName][j]); | |||||
} | |||||
this._handlers[eventName] = a; | |||||
} | |||||
} | |||||
return this; | |||||
}; | |||||
/** | |||||
* Return an event object. | |||||
* | |||||
* @param {string} events The name of the event. | |||||
* @param {?object} data The content of the event (optional). | |||||
* @return {object} Returns the instance itself. | |||||
*/ | |||||
dispatcher.prototype.getEvent = function(event, data) { | |||||
return { | |||||
type: event, | |||||
data: data || {}, | |||||
target: this | |||||
}; | |||||
}; | |||||
/** | |||||
* A useful function to deal with inheritance. It will make the target | |||||
* inherit the prototype of the class dispatcher as well as its constructor. | |||||
* | |||||
* @param {object} target The target. | |||||
*/ | |||||
dispatcher.extend = function(target, args) { | |||||
var k; | |||||
for (k in dispatcher.prototype) | |||||
if (dispatcher.prototype.hasOwnProperty(k)) | |||||
target[k] = dispatcher.prototype[k]; | |||||
dispatcher.apply(target, args); | |||||
}; | |||||
/** | |||||
* EXPORT: | |||||
* ******* | |||||
*/ | |||||
if (typeof this.sigma !== 'undefined') { | |||||
this.sigma.classes = this.sigma.classes || {}; | |||||
this.sigma.classes.dispatcher = dispatcher; | |||||
} else if (typeof exports !== 'undefined') { | |||||
if (typeof module !== 'undefined' && module.exports) | |||||
exports = module.exports = dispatcher; | |||||
exports.dispatcher = dispatcher; | |||||
} else | |||||
this.dispatcher = dispatcher; | |||||
}).call(this); |
@ -0,0 +1,832 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
/** | |||||
* Sigma Quadtree Module for edges | |||||
* =============================== | |||||
* | |||||
* Author: Sébastien Heymann, | |||||
* from the quad of Guillaume Plique (Yomguithereal) | |||||
* Version: 0.2 | |||||
*/ | |||||
/** | |||||
* Quad Geometric Operations | |||||
* ------------------------- | |||||
* | |||||
* A useful batch of geometric operations used by the quadtree. | |||||
*/ | |||||
var _geom = { | |||||
/** | |||||
* Transforms a graph node with x, y and size into an | |||||
* axis-aligned square. | |||||
* | |||||
* @param {object} A graph node with at least a point (x, y) and a size. | |||||
* @return {object} A square: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
pointToSquare: function(n) { | |||||
return { | |||||
x1: n.x - n.size, | |||||
y1: n.y - n.size, | |||||
x2: n.x + n.size, | |||||
y2: n.y - n.size, | |||||
height: n.size * 2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Transforms a graph edge with x1, y1, x2, y2 and size into an | |||||
* axis-aligned square. | |||||
* | |||||
* @param {object} A graph edge with at least two points | |||||
* (x1, y1), (x2, y2) and a size. | |||||
* @return {object} A square: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
lineToSquare: function(e) { | |||||
if (e.y1 < e.y2) { | |||||
// (e.x1, e.y1) on top | |||||
if (e.x1 < e.x2) { | |||||
// (e.x1, e.y1) on left | |||||
return { | |||||
x1: e.x1 - e.size, | |||||
y1: e.y1 - e.size, | |||||
x2: e.x2 + e.size, | |||||
y2: e.y1 - e.size, | |||||
height: e.y2 - e.y1 + e.size * 2 | |||||
}; | |||||
} | |||||
// (e.x1, e.y1) on right | |||||
return { | |||||
x1: e.x2 - e.size, | |||||
y1: e.y1 - e.size, | |||||
x2: e.x1 + e.size, | |||||
y2: e.y1 - e.size, | |||||
height: e.y2 - e.y1 + e.size * 2 | |||||
}; | |||||
} | |||||
// (e.x2, e.y2) on top | |||||
if (e.x1 < e.x2) { | |||||
// (e.x1, e.y1) on left | |||||
return { | |||||
x1: e.x1 - e.size, | |||||
y1: e.y2 - e.size, | |||||
x2: e.x2 + e.size, | |||||
y2: e.y2 - e.size, | |||||
height: e.y1 - e.y2 + e.size * 2 | |||||
}; | |||||
} | |||||
// (e.x2, e.y2) on right | |||||
return { | |||||
x1: e.x2 - e.size, | |||||
y1: e.y2 - e.size, | |||||
x2: e.x1 + e.size, | |||||
y2: e.y2 - e.size, | |||||
height: e.y1 - e.y2 + e.size * 2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Transforms a graph edge of type 'curve' with x1, y1, x2, y2, | |||||
* control point and size into an axis-aligned square. | |||||
* | |||||
* @param {object} e A graph edge with at least two points | |||||
* (x1, y1), (x2, y2) and a size. | |||||
* @param {object} cp A control point (x,y). | |||||
* @return {object} A square: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
quadraticCurveToSquare: function(e, cp) { | |||||
var pt = sigma.utils.getPointOnQuadraticCurve( | |||||
0.5, | |||||
e.x1, | |||||
e.y1, | |||||
e.x2, | |||||
e.y2, | |||||
cp.x, | |||||
cp.y | |||||
); | |||||
// Bounding box of the two points and the point at the middle of the | |||||
// curve: | |||||
var minX = Math.min(e.x1, e.x2, pt.x), | |||||
maxX = Math.max(e.x1, e.x2, pt.x), | |||||
minY = Math.min(e.y1, e.y2, pt.y), | |||||
maxY = Math.max(e.y1, e.y2, pt.y); | |||||
return { | |||||
x1: minX - e.size, | |||||
y1: minY - e.size, | |||||
x2: maxX + e.size, | |||||
y2: minY - e.size, | |||||
height: maxY - minY + e.size * 2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Transforms a graph self loop into an axis-aligned square. | |||||
* | |||||
* @param {object} n A graph node with a point (x, y) and a size. | |||||
* @return {object} A square: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
selfLoopToSquare: function(n) { | |||||
// Fitting to the curve is too costly, we compute a larger bounding box | |||||
// using the control points: | |||||
var cp = sigma.utils.getSelfLoopControlPoints(n.x, n.y, n.size); | |||||
// Bounding box of the point and the two control points: | |||||
var minX = Math.min(n.x, cp.x1, cp.x2), | |||||
maxX = Math.max(n.x, cp.x1, cp.x2), | |||||
minY = Math.min(n.y, cp.y1, cp.y2), | |||||
maxY = Math.max(n.y, cp.y1, cp.y2); | |||||
return { | |||||
x1: minX - n.size, | |||||
y1: minY - n.size, | |||||
x2: maxX + n.size, | |||||
y2: minY - n.size, | |||||
height: maxY - minY + n.size * 2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Checks whether a rectangle is axis-aligned. | |||||
* | |||||
* @param {object} A rectangle defined by two points | |||||
* (x1, y1) and (x2, y2). | |||||
* @return {boolean} True if the rectangle is axis-aligned. | |||||
*/ | |||||
isAxisAligned: function(r) { | |||||
return r.x1 === r.x2 || r.y1 === r.y2; | |||||
}, | |||||
/** | |||||
* Compute top points of an axis-aligned rectangle. This is useful in | |||||
* cases when the rectangle has been rotated (left, right or bottom up) and | |||||
* later operations need to know the top points. | |||||
* | |||||
* @param {object} An axis-aligned rectangle defined by two points | |||||
* (x1, y1), (x2, y2) and height. | |||||
* @return {object} A rectangle: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
axisAlignedTopPoints: function(r) { | |||||
// Basic | |||||
if (r.y1 === r.y2 && r.x1 < r.x2) | |||||
return r; | |||||
// Rotated to right | |||||
if (r.x1 === r.x2 && r.y2 > r.y1) | |||||
return { | |||||
x1: r.x1 - r.height, y1: r.y1, | |||||
x2: r.x1, y2: r.y1, | |||||
height: r.height | |||||
}; | |||||
// Rotated to left | |||||
if (r.x1 === r.x2 && r.y2 < r.y1) | |||||
return { | |||||
x1: r.x1, y1: r.y2, | |||||
x2: r.x2 + r.height, y2: r.y2, | |||||
height: r.height | |||||
}; | |||||
// Bottom's up | |||||
return { | |||||
x1: r.x2, y1: r.y1 - r.height, | |||||
x2: r.x1, y2: r.y1 - r.height, | |||||
height: r.height | |||||
}; | |||||
}, | |||||
/** | |||||
* Get coordinates of a rectangle's lower left corner from its top points. | |||||
* | |||||
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). | |||||
* @return {object} Coordinates of the corner (x, y). | |||||
*/ | |||||
lowerLeftCoor: function(r) { | |||||
var width = ( | |||||
Math.sqrt( | |||||
Math.pow(r.x2 - r.x1, 2) + | |||||
Math.pow(r.y2 - r.y1, 2) | |||||
) | |||||
); | |||||
return { | |||||
x: r.x1 - (r.y2 - r.y1) * r.height / width, | |||||
y: r.y1 + (r.x2 - r.x1) * r.height / width | |||||
}; | |||||
}, | |||||
/** | |||||
* Get coordinates of a rectangle's lower right corner from its top points | |||||
* and its lower left corner. | |||||
* | |||||
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). | |||||
* @param {object} A corner's coordinates (x, y). | |||||
* @return {object} Coordinates of the corner (x, y). | |||||
*/ | |||||
lowerRightCoor: function(r, llc) { | |||||
return { | |||||
x: llc.x - r.x1 + r.x2, | |||||
y: llc.y - r.y1 + r.y2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Get the coordinates of all the corners of a rectangle from its top point. | |||||
* | |||||
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). | |||||
* @return {array} An array of the four corners' coordinates (x, y). | |||||
*/ | |||||
rectangleCorners: function(r) { | |||||
var llc = this.lowerLeftCoor(r), | |||||
lrc = this.lowerRightCoor(r, llc); | |||||
return [ | |||||
{x: r.x1, y: r.y1}, | |||||
{x: r.x2, y: r.y2}, | |||||
{x: llc.x, y: llc.y}, | |||||
{x: lrc.x, y: lrc.y} | |||||
]; | |||||
}, | |||||
/** | |||||
* Split a square defined by its boundaries into four. | |||||
* | |||||
* @param {object} Boundaries of the square (x, y, width, height). | |||||
* @return {array} An array containing the four new squares, themselves | |||||
* defined by an array of their four corners (x, y). | |||||
*/ | |||||
splitSquare: function(b) { | |||||
return [ | |||||
[ | |||||
{x: b.x, y: b.y}, | |||||
{x: b.x + b.width / 2, y: b.y}, | |||||
{x: b.x, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2} | |||||
], | |||||
[ | |||||
{x: b.x + b.width / 2, y: b.y}, | |||||
{x: b.x + b.width, y: b.y}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width, y: b.y + b.height / 2} | |||||
], | |||||
[ | |||||
{x: b.x, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2}, | |||||
{x: b.x, y: b.y + b.height}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height} | |||||
], | |||||
[ | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height}, | |||||
{x: b.x + b.width, y: b.y + b.height} | |||||
] | |||||
]; | |||||
}, | |||||
/** | |||||
* Compute the four axis between corners of rectangle A and corners of | |||||
* rectangle B. This is needed later to check an eventual collision. | |||||
* | |||||
* @param {array} An array of rectangle A's four corners (x, y). | |||||
* @param {array} An array of rectangle B's four corners (x, y). | |||||
* @return {array} An array of four axis defined by their coordinates (x,y). | |||||
*/ | |||||
axis: function(c1, c2) { | |||||
return [ | |||||
{x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y}, | |||||
{x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y}, | |||||
{x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y}, | |||||
{x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y} | |||||
]; | |||||
}, | |||||
/** | |||||
* Project a rectangle's corner on an axis. | |||||
* | |||||
* @param {object} Coordinates of a corner (x, y). | |||||
* @param {object} Coordinates of an axis (x, y). | |||||
* @return {object} The projection defined by coordinates (x, y). | |||||
*/ | |||||
projection: function(c, a) { | |||||
var l = ( | |||||
(c.x * a.x + c.y * a.y) / | |||||
(Math.pow(a.x, 2) + Math.pow(a.y, 2)) | |||||
); | |||||
return { | |||||
x: l * a.x, | |||||
y: l * a.y | |||||
}; | |||||
}, | |||||
/** | |||||
* Check whether two rectangles collide on one particular axis. | |||||
* | |||||
* @param {object} An axis' coordinates (x, y). | |||||
* @param {array} Rectangle A's corners. | |||||
* @param {array} Rectangle B's corners. | |||||
* @return {boolean} True if the rectangles collide on the axis. | |||||
*/ | |||||
axisCollision: function(a, c1, c2) { | |||||
var sc1 = [], | |||||
sc2 = []; | |||||
for (var ci = 0; ci < 4; ci++) { | |||||
var p1 = this.projection(c1[ci], a), | |||||
p2 = this.projection(c2[ci], a); | |||||
sc1.push(p1.x * a.x + p1.y * a.y); | |||||
sc2.push(p2.x * a.x + p2.y * a.y); | |||||
} | |||||
var maxc1 = Math.max.apply(Math, sc1), | |||||
maxc2 = Math.max.apply(Math, sc2), | |||||
minc1 = Math.min.apply(Math, sc1), | |||||
minc2 = Math.min.apply(Math, sc2); | |||||
return (minc2 <= maxc1 && maxc2 >= minc1); | |||||
}, | |||||
/** | |||||
* Check whether two rectangles collide on each one of their four axis. If | |||||
* all axis collide, then the two rectangles do collide on the plane. | |||||
* | |||||
* @param {array} Rectangle A's corners. | |||||
* @param {array} Rectangle B's corners. | |||||
* @return {boolean} True if the rectangles collide. | |||||
*/ | |||||
collision: function(c1, c2) { | |||||
var axis = this.axis(c1, c2), | |||||
col = true; | |||||
for (var i = 0; i < 4; i++) | |||||
col = col && this.axisCollision(axis[i], c1, c2); | |||||
return col; | |||||
} | |||||
}; | |||||
/** | |||||
* Quad Functions | |||||
* ------------ | |||||
* | |||||
* The Quadtree functions themselves. | |||||
* For each of those functions, we consider that in a splitted quad, the | |||||
* index of each node is the following: | |||||
* 0: top left | |||||
* 1: top right | |||||
* 2: bottom left | |||||
* 3: bottom right | |||||
* | |||||
* Moreover, the hereafter quad's philosophy is to consider that if an element | |||||
* collides with more than one nodes, this element belongs to each of the | |||||
* nodes it collides with where other would let it lie on a higher node. | |||||
*/ | |||||
/** | |||||
* Get the index of the node containing the point in the quad | |||||
* | |||||
* @param {object} point A point defined by coordinates (x, y). | |||||
* @param {object} quadBounds Boundaries of the quad (x, y, width, heigth). | |||||
* @return {integer} The index of the node containing the point. | |||||
*/ | |||||
function _quadIndex(point, quadBounds) { | |||||
var xmp = quadBounds.x + quadBounds.width / 2, | |||||
ymp = quadBounds.y + quadBounds.height / 2, | |||||
top = (point.y < ymp), | |||||
left = (point.x < xmp); | |||||
if (top) { | |||||
if (left) | |||||
return 0; | |||||
else | |||||
return 1; | |||||
} | |||||
else { | |||||
if (left) | |||||
return 2; | |||||
else | |||||
return 3; | |||||
} | |||||
} | |||||
/** | |||||
* Get a list of indexes of nodes containing an axis-aligned rectangle | |||||
* | |||||
* @param {object} rectangle A rectangle defined by two points (x1, y1), | |||||
* (x2, y2) and height. | |||||
* @param {array} quadCorners An array of the quad nodes' corners. | |||||
* @return {array} An array of indexes containing one to | |||||
* four integers. | |||||
*/ | |||||
function _quadIndexes(rectangle, quadCorners) { | |||||
var indexes = []; | |||||
// Iterating through quads | |||||
for (var i = 0; i < 4; i++) | |||||
if ((rectangle.x2 >= quadCorners[i][0].x) && | |||||
(rectangle.x1 <= quadCorners[i][1].x) && | |||||
(rectangle.y1 + rectangle.height >= quadCorners[i][0].y) && | |||||
(rectangle.y1 <= quadCorners[i][2].y)) | |||||
indexes.push(i); | |||||
return indexes; | |||||
} | |||||
/** | |||||
* Get a list of indexes of nodes containing a non-axis-aligned rectangle | |||||
* | |||||
* @param {array} corners An array containing each corner of the | |||||
* rectangle defined by its coordinates (x, y). | |||||
* @param {array} quadCorners An array of the quad nodes' corners. | |||||
* @return {array} An array of indexes containing one to | |||||
* four integers. | |||||
*/ | |||||
function _quadCollision(corners, quadCorners) { | |||||
var indexes = []; | |||||
// Iterating through quads | |||||
for (var i = 0; i < 4; i++) | |||||
if (_geom.collision(corners, quadCorners[i])) | |||||
indexes.push(i); | |||||
return indexes; | |||||
} | |||||
/** | |||||
* Subdivide a quad by creating a node at a precise index. The function does | |||||
* not generate all four nodes not to potentially create unused nodes. | |||||
* | |||||
* @param {integer} index The index of the node to create. | |||||
* @param {object} quad The quad object to subdivide. | |||||
* @return {object} A new quad representing the node created. | |||||
*/ | |||||
function _quadSubdivide(index, quad) { | |||||
var next = quad.level + 1, | |||||
subw = Math.round(quad.bounds.width / 2), | |||||
subh = Math.round(quad.bounds.height / 2), | |||||
qx = Math.round(quad.bounds.x), | |||||
qy = Math.round(quad.bounds.y), | |||||
x, | |||||
y; | |||||
switch (index) { | |||||
case 0: | |||||
x = qx; | |||||
y = qy; | |||||
break; | |||||
case 1: | |||||
x = qx + subw; | |||||
y = qy; | |||||
break; | |||||
case 2: | |||||
x = qx; | |||||
y = qy + subh; | |||||
break; | |||||
case 3: | |||||
x = qx + subw; | |||||
y = qy + subh; | |||||
break; | |||||
} | |||||
return _quadTree( | |||||
{x: x, y: y, width: subw, height: subh}, | |||||
next, | |||||
quad.maxElements, | |||||
quad.maxLevel | |||||
); | |||||
} | |||||
/** | |||||
* Recursively insert an element into the quadtree. Only points | |||||
* with size, i.e. axis-aligned squares, may be inserted with this | |||||
* method. | |||||
* | |||||
* @param {object} el The element to insert in the quadtree. | |||||
* @param {object} sizedPoint A sized point defined by two top points | |||||
* (x1, y1), (x2, y2) and height. | |||||
* @param {object} quad The quad in which to insert the element. | |||||
* @return {undefined} The function does not return anything. | |||||
*/ | |||||
function _quadInsert(el, sizedPoint, quad) { | |||||
if (quad.level < quad.maxLevel) { | |||||
// Searching appropriate quads | |||||
var indexes = _quadIndexes(sizedPoint, quad.corners); | |||||
// Iterating | |||||
for (var i = 0, l = indexes.length; i < l; i++) { | |||||
// Subdividing if necessary | |||||
if (quad.nodes[indexes[i]] === undefined) | |||||
quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad); | |||||
// Recursion | |||||
_quadInsert(el, sizedPoint, quad.nodes[indexes[i]]); | |||||
} | |||||
} | |||||
else { | |||||
// Pushing the element in a leaf node | |||||
quad.elements.push(el); | |||||
} | |||||
} | |||||
/** | |||||
* Recursively retrieve every elements held by the node containing the | |||||
* searched point. | |||||
* | |||||
* @param {object} point The searched point (x, y). | |||||
* @param {object} quad The searched quad. | |||||
* @return {array} An array of elements contained in the relevant | |||||
* node. | |||||
*/ | |||||
function _quadRetrievePoint(point, quad) { | |||||
if (quad.level < quad.maxLevel) { | |||||
var index = _quadIndex(point, quad.bounds); | |||||
// If node does not exist we return an empty list | |||||
if (quad.nodes[index] !== undefined) { | |||||
return _quadRetrievePoint(point, quad.nodes[index]); | |||||
} | |||||
else { | |||||
return []; | |||||
} | |||||
} | |||||
else { | |||||
return quad.elements; | |||||
} | |||||
} | |||||
/** | |||||
* Recursively retrieve every elements contained within an rectangular area | |||||
* that may or may not be axis-aligned. | |||||
* | |||||
* @param {object|array} rectData The searched area defined either by | |||||
* an array of four corners (x, y) in | |||||
* the case of a non-axis-aligned | |||||
* rectangle or an object with two top | |||||
* points (x1, y1), (x2, y2) and height. | |||||
* @param {object} quad The searched quad. | |||||
* @param {function} collisionFunc The collision function used to search | |||||
* for node indexes. | |||||
* @param {array?} els The retrieved elements. | |||||
* @return {array} An array of elements contained in the | |||||
* area. | |||||
*/ | |||||
function _quadRetrieveArea(rectData, quad, collisionFunc, els) { | |||||
els = els || {}; | |||||
if (quad.level < quad.maxLevel) { | |||||
var indexes = collisionFunc(rectData, quad.corners); | |||||
for (var i = 0, l = indexes.length; i < l; i++) | |||||
if (quad.nodes[indexes[i]] !== undefined) | |||||
_quadRetrieveArea( | |||||
rectData, | |||||
quad.nodes[indexes[i]], | |||||
collisionFunc, | |||||
els | |||||
); | |||||
} else | |||||
for (var j = 0, m = quad.elements.length; j < m; j++) | |||||
if (els[quad.elements[j].id] === undefined) | |||||
els[quad.elements[j].id] = quad.elements[j]; | |||||
return els; | |||||
} | |||||
/** | |||||
* Creates the quadtree object itself. | |||||
* | |||||
* @param {object} bounds The boundaries of the quad defined by an | |||||
* origin (x, y), width and heigth. | |||||
* @param {integer} level The level of the quad in the tree. | |||||
* @param {integer} maxElements The max number of element in a leaf node. | |||||
* @param {integer} maxLevel The max recursion level of the tree. | |||||
* @return {object} The quadtree object. | |||||
*/ | |||||
function _quadTree(bounds, level, maxElements, maxLevel) { | |||||
return { | |||||
level: level || 0, | |||||
bounds: bounds, | |||||
corners: _geom.splitSquare(bounds), | |||||
maxElements: maxElements || 40, | |||||
maxLevel: maxLevel || 8, | |||||
elements: [], | |||||
nodes: [] | |||||
}; | |||||
} | |||||
/** | |||||
* Sigma Quad Constructor | |||||
* ---------------------- | |||||
* | |||||
* The edgequad API as exposed to sigma. | |||||
*/ | |||||
/** | |||||
* The edgequad core that will become the sigma interface with the quadtree. | |||||
* | |||||
* property {object} _tree Property holding the quadtree object. | |||||
* property {object} _geom Exposition of the _geom namespace for testing. | |||||
* property {object} _cache Cache for the area method. | |||||
* property {boolean} _enabled Can index and retreive elements. | |||||
*/ | |||||
var edgequad = function() { | |||||
this._geom = _geom; | |||||
this._tree = null; | |||||
this._cache = { | |||||
query: false, | |||||
result: false | |||||
}; | |||||
this._enabled = true; | |||||
}; | |||||
/** | |||||
* Index a graph by inserting its edges into the quadtree. | |||||
* | |||||
* @param {object} graph A graph instance. | |||||
* @param {object} params An object of parameters with at least the quad | |||||
* bounds. | |||||
* @return {object} The quadtree object. | |||||
* | |||||
* Parameters: | |||||
* ---------- | |||||
* bounds: {object} boundaries of the quad defined by its origin (x, y) | |||||
* width and heigth. | |||||
* prefix: {string?} a prefix for edge geometric attributes. | |||||
* maxElements: {integer?} the max number of elements in a leaf node. | |||||
* maxLevel: {integer?} the max recursion level of the tree. | |||||
*/ | |||||
edgequad.prototype.index = function(graph, params) { | |||||
if (!this._enabled) | |||||
return this._tree; | |||||
// Enforcing presence of boundaries | |||||
if (!params.bounds) | |||||
throw 'sigma.classes.edgequad.index: bounds information not given.'; | |||||
// Prefix | |||||
var prefix = params.prefix || '', | |||||
cp, | |||||
source, | |||||
target, | |||||
n, | |||||
e; | |||||
// Building the tree | |||||
this._tree = _quadTree( | |||||
params.bounds, | |||||
0, | |||||
params.maxElements, | |||||
params.maxLevel | |||||
); | |||||
var edges = graph.edges(); | |||||
// Inserting graph edges into the tree | |||||
for (var i = 0, l = edges.length; i < l; i++) { | |||||
source = graph.nodes(edges[i].source); | |||||
target = graph.nodes(edges[i].target); | |||||
e = { | |||||
x1: source[prefix + 'x'], | |||||
y1: source[prefix + 'y'], | |||||
x2: target[prefix + 'x'], | |||||
y2: target[prefix + 'y'], | |||||
size: edges[i][prefix + 'size'] || 0 | |||||
}; | |||||
// Inserting edge | |||||
if (edges[i].type === 'curve' || edges[i].type === 'curvedArrow') { | |||||
if (source.id === target.id) { | |||||
n = { | |||||
x: source[prefix + 'x'], | |||||
y: source[prefix + 'y'], | |||||
size: source[prefix + 'size'] || 0 | |||||
}; | |||||
_quadInsert( | |||||
edges[i], | |||||
_geom.selfLoopToSquare(n), | |||||
this._tree); | |||||
} | |||||
else { | |||||
cp = sigma.utils.getQuadraticControlPoint(e.x1, e.y1, e.x2, e.y2); | |||||
_quadInsert( | |||||
edges[i], | |||||
_geom.quadraticCurveToSquare(e, cp), | |||||
this._tree); | |||||
} | |||||
} | |||||
else { | |||||
_quadInsert( | |||||
edges[i], | |||||
_geom.lineToSquare(e), | |||||
this._tree); | |||||
} | |||||
} | |||||
// Reset cache: | |||||
this._cache = { | |||||
query: false, | |||||
result: false | |||||
}; | |||||
// remove? | |||||
return this._tree; | |||||
}; | |||||
/** | |||||
* Retrieve every graph edges held by the quadtree node containing the | |||||
* searched point. | |||||
* | |||||
* @param {number} x of the point. | |||||
* @param {number} y of the point. | |||||
* @return {array} An array of edges retrieved. | |||||
*/ | |||||
edgequad.prototype.point = function(x, y) { | |||||
if (!this._enabled) | |||||
return []; | |||||
return this._tree ? | |||||
_quadRetrievePoint({x: x, y: y}, this._tree) || [] : | |||||
[]; | |||||
}; | |||||
/** | |||||
* Retrieve every graph edges within a rectangular area. The methods keep the | |||||
* last area queried in cache for optimization reason and will act differently | |||||
* for the same reason if the area is axis-aligned or not. | |||||
* | |||||
* @param {object} A rectangle defined by two top points (x1, y1), (x2, y2) | |||||
* and height. | |||||
* @return {array} An array of edges retrieved. | |||||
*/ | |||||
edgequad.prototype.area = function(rect) { | |||||
if (!this._enabled) | |||||
return []; | |||||
var serialized = JSON.stringify(rect), | |||||
collisionFunc, | |||||
rectData; | |||||
// Returning cache? | |||||
if (this._cache.query === serialized) | |||||
return this._cache.result; | |||||
// Axis aligned ? | |||||
if (_geom.isAxisAligned(rect)) { | |||||
collisionFunc = _quadIndexes; | |||||
rectData = _geom.axisAlignedTopPoints(rect); | |||||
} | |||||
else { | |||||
collisionFunc = _quadCollision; | |||||
rectData = _geom.rectangleCorners(rect); | |||||
} | |||||
// Retrieving edges | |||||
var edges = this._tree ? | |||||
_quadRetrieveArea( | |||||
rectData, | |||||
this._tree, | |||||
collisionFunc | |||||
) : | |||||
[]; | |||||
// Object to array | |||||
var edgesArray = []; | |||||
for (var i in edges) | |||||
edgesArray.push(edges[i]); | |||||
// Caching | |||||
this._cache.query = serialized; | |||||
this._cache.result = edgesArray; | |||||
return edgesArray; | |||||
}; | |||||
/** | |||||
* EXPORT: | |||||
* ******* | |||||
*/ | |||||
if (typeof this.sigma !== 'undefined') { | |||||
this.sigma.classes = this.sigma.classes || {}; | |||||
this.sigma.classes.edgequad = edgequad; | |||||
} else if (typeof exports !== 'undefined') { | |||||
if (typeof module !== 'undefined' && module.exports) | |||||
exports = module.exports = edgequad; | |||||
exports.edgequad = edgequad; | |||||
} else | |||||
this.edgequad = edgequad; | |||||
}).call(this); |
@ -0,0 +1,859 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
var _methods = Object.create(null), | |||||
_indexes = Object.create(null), | |||||
_initBindings = Object.create(null), | |||||
_methodBindings = Object.create(null), | |||||
_methodBeforeBindings = Object.create(null), | |||||
_defaultSettings = { | |||||
immutable: true, | |||||
clone: true | |||||
}, | |||||
_defaultSettingsFunction = function(key) { | |||||
return _defaultSettings[key]; | |||||
}; | |||||
/** | |||||
* The graph constructor. It initializes the data and the indexes, and binds | |||||
* the custom indexes and methods to its own scope. | |||||
* | |||||
* Recognized parameters: | |||||
* ********************** | |||||
* Here is the exhaustive list of every accepted parameters in the settings | |||||
* object: | |||||
* | |||||
* {boolean} clone Indicates if the data have to be cloned in methods | |||||
* to add nodes or edges. | |||||
* {boolean} immutable Indicates if nodes "id" values and edges "id", | |||||
* "source" and "target" values must be set as | |||||
* immutable. | |||||
* | |||||
* @param {?configurable} settings Eventually a settings function. | |||||
* @return {graph} The new graph instance. | |||||
*/ | |||||
var graph = function(settings) { | |||||
var k, | |||||
fn, | |||||
data; | |||||
/** | |||||
* DATA: | |||||
* ***** | |||||
* Every data that is callable from graph methods are stored in this "data" | |||||
* object. This object will be served as context for all these methods, | |||||
* and it is possible to add other type of data in it. | |||||
*/ | |||||
data = { | |||||
/** | |||||
* SETTINGS FUNCTION: | |||||
* ****************** | |||||
*/ | |||||
settings: settings || _defaultSettingsFunction, | |||||
/** | |||||
* MAIN DATA: | |||||
* ********** | |||||
*/ | |||||
nodesArray: [], | |||||
edgesArray: [], | |||||
/** | |||||
* GLOBAL INDEXES: | |||||
* *************** | |||||
* These indexes just index data by ids. | |||||
*/ | |||||
nodesIndex: Object.create(null), | |||||
edgesIndex: Object.create(null), | |||||
/** | |||||
* LOCAL INDEXES: | |||||
* ************** | |||||
* These indexes refer from node to nodes. Each key is an id, and each | |||||
* value is the array of the ids of related nodes. | |||||
*/ | |||||
inNeighborsIndex: Object.create(null), | |||||
outNeighborsIndex: Object.create(null), | |||||
allNeighborsIndex: Object.create(null), | |||||
inNeighborsCount: Object.create(null), | |||||
outNeighborsCount: Object.create(null), | |||||
allNeighborsCount: Object.create(null) | |||||
}; | |||||
// Execute bindings: | |||||
for (k in _initBindings) | |||||
_initBindings[k].call(data); | |||||
// Add methods to both the scope and the data objects: | |||||
for (k in _methods) { | |||||
fn = __bindGraphMethod(k, data, _methods[k]); | |||||
this[k] = fn; | |||||
data[k] = fn; | |||||
} | |||||
}; | |||||
/** | |||||
* A custom tool to bind methods such that function that are bound to it will | |||||
* be executed anytime the method is called. | |||||
* | |||||
* @param {string} methodName The name of the method to bind. | |||||
* @param {object} scope The scope where the method must be executed. | |||||
* @param {function} fn The method itself. | |||||
* @return {function} The new method. | |||||
*/ | |||||
function __bindGraphMethod(methodName, scope, fn) { | |||||
var result = function() { | |||||
var k, | |||||
res; | |||||
// Execute "before" bound functions: | |||||
for (k in _methodBeforeBindings[methodName]) | |||||
_methodBeforeBindings[methodName][k].apply(scope, arguments); | |||||
// Apply the method: | |||||
res = fn.apply(scope, arguments); | |||||
// Execute bound functions: | |||||
for (k in _methodBindings[methodName]) | |||||
_methodBindings[methodName][k].apply(scope, arguments); | |||||
// Return res: | |||||
return res; | |||||
}; | |||||
return result; | |||||
} | |||||
/** | |||||
* This custom tool function removes every pair key/value from an hash. The | |||||
* goal is to avoid creating a new object while some other references are | |||||
* still hanging in some scopes... | |||||
* | |||||
* @param {object} obj The object to empty. | |||||
* @return {object} The empty object. | |||||
*/ | |||||
function __emptyObject(obj) { | |||||
var k; | |||||
for (k in obj) | |||||
if (!('hasOwnProperty' in obj) || obj.hasOwnProperty(k)) | |||||
delete obj[k]; | |||||
return obj; | |||||
} | |||||
/** | |||||
* This global method adds a method that will be bound to the futurly created | |||||
* graph instances. | |||||
* | |||||
* Since these methods will be bound to their scope when the instances are | |||||
* created, it does not use the prototype. Because of that, methods have to | |||||
* be added before instances are created to make them available. | |||||
* | |||||
* Here is an example: | |||||
* | |||||
* > graph.addMethod('getNodesCount', function() { | |||||
* > return this.nodesArray.length; | |||||
* > }); | |||||
* > | |||||
* > var myGraph = new graph(); | |||||
* > console.log(myGraph.getNodesCount()); // outputs 0 | |||||
* | |||||
* @param {string} methodName The name of the method. | |||||
* @param {function} fn The method itself. | |||||
* @return {object} The global graph constructor. | |||||
*/ | |||||
graph.addMethod = function(methodName, fn) { | |||||
if ( | |||||
typeof methodName !== 'string' || | |||||
typeof fn !== 'function' || | |||||
arguments.length !== 2 | |||||
) | |||||
throw 'addMethod: Wrong arguments.'; | |||||
if (_methods[methodName] || graph[methodName]) | |||||
throw 'The method "' + methodName + '" already exists.'; | |||||
_methods[methodName] = fn; | |||||
_methodBindings[methodName] = Object.create(null); | |||||
_methodBeforeBindings[methodName] = Object.create(null); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This global method returns true if the method has already been added, and | |||||
* false else. | |||||
* | |||||
* Here are some examples: | |||||
* | |||||
* > graph.hasMethod('addNode'); // returns true | |||||
* > graph.hasMethod('hasMethod'); // returns true | |||||
* > graph.hasMethod('unexistingMethod'); // returns false | |||||
* | |||||
* @param {string} methodName The name of the method. | |||||
* @return {boolean} The result. | |||||
*/ | |||||
graph.hasMethod = function(methodName) { | |||||
return !!(_methods[methodName] || graph[methodName]); | |||||
}; | |||||
/** | |||||
* This global methods attaches a function to a method. Anytime the specified | |||||
* method is called, the attached function is called right after, with the | |||||
* same arguments and in the same scope. The attached function is called | |||||
* right before if the last argument is true, unless the method is the graph | |||||
* constructor. | |||||
* | |||||
* To attach a function to the graph constructor, use 'constructor' as the | |||||
* method name (first argument). | |||||
* | |||||
* The main idea is to have a clean way to keep custom indexes up to date, | |||||
* for instance: | |||||
* | |||||
* > var timesAddNodeCalled = 0; | |||||
* > graph.attach('addNode', 'timesAddNodeCalledInc', function() { | |||||
* > timesAddNodeCalled++; | |||||
* > }); | |||||
* > | |||||
* > var myGraph = new graph(); | |||||
* > console.log(timesAddNodeCalled); // outputs 0 | |||||
* > | |||||
* > myGraph.addNode({ id: '1' }).addNode({ id: '2' }); | |||||
* > console.log(timesAddNodeCalled); // outputs 2 | |||||
* | |||||
* The idea for calling a function before is to provide pre-processors, for | |||||
* instance: | |||||
* | |||||
* > var colorPalette = { Person: '#C3CBE1', Place: '#9BDEBD' }; | |||||
* > graph.attach('addNode', 'applyNodeColorPalette', function(n) { | |||||
* > n.color = colorPalette[n.category]; | |||||
* > }, true); | |||||
* > | |||||
* > var myGraph = new graph(); | |||||
* > myGraph.addNode({ id: 'n0', category: 'Person' }); | |||||
* > console.log(myGraph.nodes('n0').color); // outputs '#C3CBE1' | |||||
* | |||||
* @param {string} methodName The name of the related method or | |||||
* "constructor". | |||||
* @param {string} key The key to identify the function to attach. | |||||
* @param {function} fn The function to bind. | |||||
* @param {boolean} before If true the function is called right before. | |||||
* @return {object} The global graph constructor. | |||||
*/ | |||||
graph.attach = function(methodName, key, fn, before) { | |||||
if ( | |||||
typeof methodName !== 'string' || | |||||
typeof key !== 'string' || | |||||
typeof fn !== 'function' || | |||||
arguments.length < 3 || | |||||
arguments.length > 4 | |||||
) | |||||
throw 'attach: Wrong arguments.'; | |||||
var bindings; | |||||
if (methodName === 'constructor') | |||||
bindings = _initBindings; | |||||
else { | |||||
if (before) { | |||||
if (!_methodBeforeBindings[methodName]) | |||||
throw 'The method "' + methodName + '" does not exist.'; | |||||
bindings = _methodBeforeBindings[methodName]; | |||||
} | |||||
else { | |||||
if (!_methodBindings[methodName]) | |||||
throw 'The method "' + methodName + '" does not exist.'; | |||||
bindings = _methodBindings[methodName]; | |||||
} | |||||
} | |||||
if (bindings[key]) | |||||
throw 'A function "' + key + '" is already attached ' + | |||||
'to the method "' + methodName + '".'; | |||||
bindings[key] = fn; | |||||
return this; | |||||
}; | |||||
/** | |||||
* Alias of attach(methodName, key, fn, true). | |||||
*/ | |||||
graph.attachBefore = function(methodName, key, fn) { | |||||
return this.attach(methodName, key, fn, true); | |||||
}; | |||||
/** | |||||
* This methods is just an helper to deal with custom indexes. It takes as | |||||
* arguments the name of the index and an object containing all the different | |||||
* functions to bind to the methods. | |||||
* | |||||
* Here is a basic example, that creates an index to keep the number of nodes | |||||
* in the current graph. It also adds a method to provide a getter on that | |||||
* new index: | |||||
* | |||||
* > sigma.classes.graph.addIndex('nodesCount', { | |||||
* > constructor: function() { | |||||
* > this.nodesCount = 0; | |||||
* > }, | |||||
* > addNode: function() { | |||||
* > this.nodesCount++; | |||||
* > }, | |||||
* > dropNode: function() { | |||||
* > this.nodesCount--; | |||||
* > } | |||||
* > }); | |||||
* > | |||||
* > sigma.classes.graph.addMethod('getNodesCount', function() { | |||||
* > return this.nodesCount; | |||||
* > }); | |||||
* > | |||||
* > var myGraph = new sigma.classes.graph(); | |||||
* > console.log(myGraph.getNodesCount()); // outputs 0 | |||||
* > | |||||
* > myGraph.addNode({ id: '1' }).addNode({ id: '2' }); | |||||
* > console.log(myGraph.getNodesCount()); // outputs 2 | |||||
* | |||||
* @param {string} name The name of the index. | |||||
* @param {object} bindings The object containing the functions to bind. | |||||
* @return {object} The global graph constructor. | |||||
*/ | |||||
graph.addIndex = function(name, bindings) { | |||||
if ( | |||||
typeof name !== 'string' || | |||||
Object(bindings) !== bindings || | |||||
arguments.length !== 2 | |||||
) | |||||
throw 'addIndex: Wrong arguments.'; | |||||
if (_indexes[name]) | |||||
throw 'The index "' + name + '" already exists.'; | |||||
var k; | |||||
// Store the bindings: | |||||
_indexes[name] = bindings; | |||||
// Attach the bindings: | |||||
for (k in bindings) | |||||
if (typeof bindings[k] !== 'function') | |||||
throw 'The bindings must be functions.'; | |||||
else | |||||
graph.attach(k, name, bindings[k]); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method adds a node to the graph. The node must be an object, with a | |||||
* string under the key "id". Except for this, it is possible to add any | |||||
* other attribute, that will be preserved all along the manipulations. | |||||
* | |||||
* If the graph option "clone" has a truthy value, the node will be cloned | |||||
* when added to the graph. Also, if the graph option "immutable" has a | |||||
* truthy value, its id will be defined as immutable. | |||||
* | |||||
* @param {object} node The node to add. | |||||
* @return {object} The graph instance. | |||||
*/ | |||||
graph.addMethod('addNode', function(node) { | |||||
// Check that the node is an object and has an id: | |||||
if (Object(node) !== node || arguments.length !== 1) | |||||
throw 'addNode: Wrong arguments.'; | |||||
if (typeof node.id !== 'string' && typeof node.id !== 'number') | |||||
throw 'The node must have a string or number id.'; | |||||
if (this.nodesIndex[node.id]) | |||||
throw 'The node "' + node.id + '" already exists.'; | |||||
var k, | |||||
id = node.id, | |||||
validNode = Object.create(null); | |||||
// Check the "clone" option: | |||||
if (this.settings('clone')) { | |||||
for (k in node) | |||||
if (k !== 'id') | |||||
validNode[k] = node[k]; | |||||
} else | |||||
validNode = node; | |||||
// Check the "immutable" option: | |||||
if (this.settings('immutable')) | |||||
Object.defineProperty(validNode, 'id', { | |||||
value: id, | |||||
enumerable: true | |||||
}); | |||||
else | |||||
validNode.id = id; | |||||
// Add empty containers for edges indexes: | |||||
this.inNeighborsIndex[id] = Object.create(null); | |||||
this.outNeighborsIndex[id] = Object.create(null); | |||||
this.allNeighborsIndex[id] = Object.create(null); | |||||
this.inNeighborsCount[id] = 0; | |||||
this.outNeighborsCount[id] = 0; | |||||
this.allNeighborsCount[id] = 0; | |||||
// Add the node to indexes: | |||||
this.nodesArray.push(validNode); | |||||
this.nodesIndex[validNode.id] = validNode; | |||||
// Return the current instance: | |||||
return this; | |||||
}); | |||||
/** | |||||
* This method adds an edge to the graph. The edge must be an object, with a | |||||
* string under the key "id", and strings under the keys "source" and | |||||
* "target" that design existing nodes. Except for this, it is possible to | |||||
* add any other attribute, that will be preserved all along the | |||||
* manipulations. | |||||
* | |||||
* If the graph option "clone" has a truthy value, the edge will be cloned | |||||
* when added to the graph. Also, if the graph option "immutable" has a | |||||
* truthy value, its id, source and target will be defined as immutable. | |||||
* | |||||
* @param {object} edge The edge to add. | |||||
* @return {object} The graph instance. | |||||
*/ | |||||
graph.addMethod('addEdge', function(edge) { | |||||
// Check that the edge is an object and has an id: | |||||
if (Object(edge) !== edge || arguments.length !== 1) | |||||
throw 'addEdge: Wrong arguments.'; | |||||
if (typeof edge.id !== 'string' && typeof edge.id !== 'number') | |||||
throw 'The edge must have a string or number id.'; | |||||
if ((typeof edge.source !== 'string' && typeof edge.source !== 'number') || | |||||
!this.nodesIndex[edge.source]) | |||||
throw 'The edge source must have an existing node id.'; | |||||
if ((typeof edge.target !== 'string' && typeof edge.target !== 'number') || | |||||
!this.nodesIndex[edge.target]) | |||||
throw 'The edge target must have an existing node id.'; | |||||
if (this.edgesIndex[edge.id]) | |||||
throw 'The edge "' + edge.id + '" already exists.'; | |||||
var k, | |||||
validEdge = Object.create(null); | |||||
// Check the "clone" option: | |||||
if (this.settings('clone')) { | |||||
for (k in edge) | |||||
if (k !== 'id' && k !== 'source' && k !== 'target') | |||||
validEdge[k] = edge[k]; | |||||
} else | |||||
validEdge = edge; | |||||
// Check the "immutable" option: | |||||
if (this.settings('immutable')) { | |||||
Object.defineProperty(validEdge, 'id', { | |||||
value: edge.id, | |||||
enumerable: true | |||||
}); | |||||
Object.defineProperty(validEdge, 'source', { | |||||
value: edge.source, | |||||
enumerable: true | |||||
}); | |||||
Object.defineProperty(validEdge, 'target', { | |||||
value: edge.target, | |||||
enumerable: true | |||||
}); | |||||
} else { | |||||
validEdge.id = edge.id; | |||||
validEdge.source = edge.source; | |||||
validEdge.target = edge.target; | |||||
} | |||||
// Add the edge to indexes: | |||||
this.edgesArray.push(validEdge); | |||||
this.edgesIndex[validEdge.id] = validEdge; | |||||
if (!this.inNeighborsIndex[validEdge.target][validEdge.source]) | |||||
this.inNeighborsIndex[validEdge.target][validEdge.source] = | |||||
Object.create(null); | |||||
this.inNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] = | |||||
validEdge; | |||||
if (!this.outNeighborsIndex[validEdge.source][validEdge.target]) | |||||
this.outNeighborsIndex[validEdge.source][validEdge.target] = | |||||
Object.create(null); | |||||
this.outNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] = | |||||
validEdge; | |||||
if (!this.allNeighborsIndex[validEdge.source][validEdge.target]) | |||||
this.allNeighborsIndex[validEdge.source][validEdge.target] = | |||||
Object.create(null); | |||||
this.allNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] = | |||||
validEdge; | |||||
if (validEdge.target !== validEdge.source) { | |||||
if (!this.allNeighborsIndex[validEdge.target][validEdge.source]) | |||||
this.allNeighborsIndex[validEdge.target][validEdge.source] = | |||||
Object.create(null); | |||||
this.allNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] = | |||||
validEdge; | |||||
} | |||||
// Keep counts up to date: | |||||
this.inNeighborsCount[validEdge.target]++; | |||||
this.outNeighborsCount[validEdge.source]++; | |||||
this.allNeighborsCount[validEdge.target]++; | |||||
this.allNeighborsCount[validEdge.source]++; | |||||
return this; | |||||
}); | |||||
/** | |||||
* This method drops a node from the graph. It also removes each edge that is | |||||
* bound to it, through the dropEdge method. An error is thrown if the node | |||||
* does not exist. | |||||
* | |||||
* @param {string} id The node id. | |||||
* @return {object} The graph instance. | |||||
*/ | |||||
graph.addMethod('dropNode', function(id) { | |||||
// Check that the arguments are valid: | |||||
if ((typeof id !== 'string' && typeof id !== 'number') || | |||||
arguments.length !== 1) | |||||
throw 'dropNode: Wrong arguments.'; | |||||
if (!this.nodesIndex[id]) | |||||
throw 'The node "' + id + '" does not exist.'; | |||||
var i, k, l; | |||||
// Remove the node from indexes: | |||||
delete this.nodesIndex[id]; | |||||
for (i = 0, l = this.nodesArray.length; i < l; i++) | |||||
if (this.nodesArray[i].id === id) { | |||||
this.nodesArray.splice(i, 1); | |||||
break; | |||||
} | |||||
// Remove related edges: | |||||
for (i = this.edgesArray.length - 1; i >= 0; i--) | |||||
if (this.edgesArray[i].source === id || this.edgesArray[i].target === id) | |||||
this.dropEdge(this.edgesArray[i].id); | |||||
// Remove related edge indexes: | |||||
delete this.inNeighborsIndex[id]; | |||||
delete this.outNeighborsIndex[id]; | |||||
delete this.allNeighborsIndex[id]; | |||||
delete this.inNeighborsCount[id]; | |||||
delete this.outNeighborsCount[id]; | |||||
delete this.allNeighborsCount[id]; | |||||
for (k in this.nodesIndex) { | |||||
delete this.inNeighborsIndex[k][id]; | |||||
delete this.outNeighborsIndex[k][id]; | |||||
delete this.allNeighborsIndex[k][id]; | |||||
} | |||||
return this; | |||||
}); | |||||
/** | |||||
* This method drops an edge from the graph. An error is thrown if the edge | |||||
* does not exist. | |||||
* | |||||
* @param {string} id The edge id. | |||||
* @return {object} The graph instance. | |||||
*/ | |||||
graph.addMethod('dropEdge', function(id) { | |||||
// Check that the arguments are valid: | |||||
if ((typeof id !== 'string' && typeof id !== 'number') || | |||||
arguments.length !== 1) | |||||
throw 'dropEdge: Wrong arguments.'; | |||||
if (!this.edgesIndex[id]) | |||||
throw 'The edge "' + id + '" does not exist.'; | |||||
var i, l, edge; | |||||
// Remove the edge from indexes: | |||||
edge = this.edgesIndex[id]; | |||||
delete this.edgesIndex[id]; | |||||
for (i = 0, l = this.edgesArray.length; i < l; i++) | |||||
if (this.edgesArray[i].id === id) { | |||||
this.edgesArray.splice(i, 1); | |||||
break; | |||||
} | |||||
delete this.inNeighborsIndex[edge.target][edge.source][edge.id]; | |||||
if (!Object.keys(this.inNeighborsIndex[edge.target][edge.source]).length) | |||||
delete this.inNeighborsIndex[edge.target][edge.source]; | |||||
delete this.outNeighborsIndex[edge.source][edge.target][edge.id]; | |||||
if (!Object.keys(this.outNeighborsIndex[edge.source][edge.target]).length) | |||||
delete this.outNeighborsIndex[edge.source][edge.target]; | |||||
delete this.allNeighborsIndex[edge.source][edge.target][edge.id]; | |||||
if (!Object.keys(this.allNeighborsIndex[edge.source][edge.target]).length) | |||||
delete this.allNeighborsIndex[edge.source][edge.target]; | |||||
if (edge.target !== edge.source) { | |||||
delete this.allNeighborsIndex[edge.target][edge.source][edge.id]; | |||||
if (!Object.keys(this.allNeighborsIndex[edge.target][edge.source]).length) | |||||
delete this.allNeighborsIndex[edge.target][edge.source]; | |||||
} | |||||
this.inNeighborsCount[edge.target]--; | |||||
this.outNeighborsCount[edge.source]--; | |||||
this.allNeighborsCount[edge.source]--; | |||||
this.allNeighborsCount[edge.target]--; | |||||
return this; | |||||
}); | |||||
/** | |||||
* This method destroys the current instance. It basically empties each index | |||||
* and methods attached to the graph. | |||||
*/ | |||||
graph.addMethod('kill', function() { | |||||
// Delete arrays: | |||||
this.nodesArray.length = 0; | |||||
this.edgesArray.length = 0; | |||||
delete this.nodesArray; | |||||
delete this.edgesArray; | |||||
// Delete indexes: | |||||
delete this.nodesIndex; | |||||
delete this.edgesIndex; | |||||
delete this.inNeighborsIndex; | |||||
delete this.outNeighborsIndex; | |||||
delete this.allNeighborsIndex; | |||||
delete this.inNeighborsCount; | |||||
delete this.outNeighborsCount; | |||||
delete this.allNeighborsCount; | |||||
}); | |||||
/** | |||||
* This method empties the nodes and edges arrays, as well as the different | |||||
* indexes. | |||||
* | |||||
* @return {object} The graph instance. | |||||
*/ | |||||
graph.addMethod('clear', function() { | |||||
this.nodesArray.length = 0; | |||||
this.edgesArray.length = 0; | |||||
// Due to GC issues, I prefer not to create new object. These objects are | |||||
// only available from the methods and attached functions, but still, it is | |||||
// better to prevent ghost references to unrelevant data... | |||||
__emptyObject(this.nodesIndex); | |||||
__emptyObject(this.edgesIndex); | |||||
__emptyObject(this.nodesIndex); | |||||
__emptyObject(this.inNeighborsIndex); | |||||
__emptyObject(this.outNeighborsIndex); | |||||
__emptyObject(this.allNeighborsIndex); | |||||
__emptyObject(this.inNeighborsCount); | |||||
__emptyObject(this.outNeighborsCount); | |||||
__emptyObject(this.allNeighborsCount); | |||||
return this; | |||||
}); | |||||
/** | |||||
* This method reads an object and adds the nodes and edges, through the | |||||
* proper methods "addNode" and "addEdge". | |||||
* | |||||
* Here is an example: | |||||
* | |||||
* > var myGraph = new graph(); | |||||
* > myGraph.read({ | |||||
* > nodes: [ | |||||
* > { id: 'n0' }, | |||||
* > { id: 'n1' } | |||||
* > ], | |||||
* > edges: [ | |||||
* > { | |||||
* > id: 'e0', | |||||
* > source: 'n0', | |||||
* > target: 'n1' | |||||
* > } | |||||
* > ] | |||||
* > }); | |||||
* > | |||||
* > console.log( | |||||
* > myGraph.nodes().length, | |||||
* > myGraph.edges().length | |||||
* > ); // outputs 2 1 | |||||
* | |||||
* @param {object} g The graph object. | |||||
* @return {object} The graph instance. | |||||
*/ | |||||
graph.addMethod('read', function(g) { | |||||
var i, | |||||
a, | |||||
l; | |||||
a = g.nodes || []; | |||||
for (i = 0, l = a.length; i < l; i++) | |||||
this.addNode(a[i]); | |||||
a = g.edges || []; | |||||
for (i = 0, l = a.length; i < l; i++) | |||||
this.addEdge(a[i]); | |||||
return this; | |||||
}); | |||||
/** | |||||
* This methods returns one or several nodes, depending on how it is called. | |||||
* | |||||
* To get the array of nodes, call "nodes" without argument. To get a | |||||
* specific node, call it with the id of the node. The get multiple node, | |||||
* call it with an array of ids, and it will return the array of nodes, in | |||||
* the same order. | |||||
* | |||||
* @param {?(string|array)} v Eventually one id, an array of ids. | |||||
* @return {object|array} The related node or array of nodes. | |||||
*/ | |||||
graph.addMethod('nodes', function(v) { | |||||
// Clone the array of nodes and return it: | |||||
if (!arguments.length) | |||||
return this.nodesArray.slice(0); | |||||
// Return the related node: | |||||
if (arguments.length === 1 && | |||||
(typeof v === 'string' || typeof v === 'number')) | |||||
return this.nodesIndex[v]; | |||||
// Return an array of the related node: | |||||
if ( | |||||
arguments.length === 1 && | |||||
Object.prototype.toString.call(v) === '[object Array]' | |||||
) { | |||||
var i, | |||||
l, | |||||
a = []; | |||||
for (i = 0, l = v.length; i < l; i++) | |||||
if (typeof v[i] === 'string' || typeof v[i] === 'number') | |||||
a.push(this.nodesIndex[v[i]]); | |||||
else | |||||
throw 'nodes: Wrong arguments.'; | |||||
return a; | |||||
} | |||||
throw 'nodes: Wrong arguments.'; | |||||
}); | |||||
/** | |||||
* This methods returns the degree of one or several nodes, depending on how | |||||
* it is called. It is also possible to get incoming or outcoming degrees | |||||
* instead by specifying 'in' or 'out' as a second argument. | |||||
* | |||||
* @param {string|array} v One id, an array of ids. | |||||
* @param {?string} which Which degree is required. Values are 'in', | |||||
* 'out', and by default the normal degree. | |||||
* @return {number|array} The related degree or array of degrees. | |||||
*/ | |||||
graph.addMethod('degree', function(v, which) { | |||||
// Check which degree is required: | |||||
which = { | |||||
'in': this.inNeighborsCount, | |||||
'out': this.outNeighborsCount | |||||
}[which || ''] || this.allNeighborsCount; | |||||
// Return the related node: | |||||
if (typeof v === 'string' || typeof v === 'number') | |||||
return which[v]; | |||||
// Return an array of the related node: | |||||
if (Object.prototype.toString.call(v) === '[object Array]') { | |||||
var i, | |||||
l, | |||||
a = []; | |||||
for (i = 0, l = v.length; i < l; i++) | |||||
if (typeof v[i] === 'string' || typeof v[i] === 'number') | |||||
a.push(which[v[i]]); | |||||
else | |||||
throw 'degree: Wrong arguments.'; | |||||
return a; | |||||
} | |||||
throw 'degree: Wrong arguments.'; | |||||
}); | |||||
/** | |||||
* This methods returns one or several edges, depending on how it is called. | |||||
* | |||||
* To get the array of edges, call "edges" without argument. To get a | |||||
* specific edge, call it with the id of the edge. The get multiple edge, | |||||
* call it with an array of ids, and it will return the array of edges, in | |||||
* the same order. | |||||
* | |||||
* @param {?(string|array)} v Eventually one id, an array of ids. | |||||
* @return {object|array} The related edge or array of edges. | |||||
*/ | |||||
graph.addMethod('edges', function(v) { | |||||
// Clone the array of edges and return it: | |||||
if (!arguments.length) | |||||
return this.edgesArray.slice(0); | |||||
// Return the related edge: | |||||
if (arguments.length === 1 && | |||||
(typeof v === 'string' || typeof v === 'number')) | |||||
return this.edgesIndex[v]; | |||||
// Return an array of the related edge: | |||||
if ( | |||||
arguments.length === 1 && | |||||
Object.prototype.toString.call(v) === '[object Array]' | |||||
) { | |||||
var i, | |||||
l, | |||||
a = []; | |||||
for (i = 0, l = v.length; i < l; i++) | |||||
if (typeof v[i] === 'string' || typeof v[i] === 'number') | |||||
a.push(this.edgesIndex[v[i]]); | |||||
else | |||||
throw 'edges: Wrong arguments.'; | |||||
return a; | |||||
} | |||||
throw 'edges: Wrong arguments.'; | |||||
}); | |||||
/** | |||||
* EXPORT: | |||||
* ******* | |||||
*/ | |||||
if (typeof sigma !== 'undefined') { | |||||
sigma.classes = sigma.classes || Object.create(null); | |||||
sigma.classes.graph = graph; | |||||
} else if (typeof exports !== 'undefined') { | |||||
if (typeof module !== 'undefined' && module.exports) | |||||
exports = module.exports = graph; | |||||
exports.graph = graph; | |||||
} else | |||||
this.graph = graph; | |||||
}).call(this); |
@ -0,0 +1,674 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
/** | |||||
* Sigma Quadtree Module | |||||
* ===================== | |||||
* | |||||
* Author: Guillaume Plique (Yomguithereal) | |||||
* Version: 0.2 | |||||
*/ | |||||
/** | |||||
* Quad Geometric Operations | |||||
* ------------------------- | |||||
* | |||||
* A useful batch of geometric operations used by the quadtree. | |||||
*/ | |||||
var _geom = { | |||||
/** | |||||
* Transforms a graph node with x, y and size into an | |||||
* axis-aligned square. | |||||
* | |||||
* @param {object} A graph node with at least a point (x, y) and a size. | |||||
* @return {object} A square: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
pointToSquare: function(n) { | |||||
return { | |||||
x1: n.x - n.size, | |||||
y1: n.y - n.size, | |||||
x2: n.x + n.size, | |||||
y2: n.y - n.size, | |||||
height: n.size * 2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Checks whether a rectangle is axis-aligned. | |||||
* | |||||
* @param {object} A rectangle defined by two points | |||||
* (x1, y1) and (x2, y2). | |||||
* @return {boolean} True if the rectangle is axis-aligned. | |||||
*/ | |||||
isAxisAligned: function(r) { | |||||
return r.x1 === r.x2 || r.y1 === r.y2; | |||||
}, | |||||
/** | |||||
* Compute top points of an axis-aligned rectangle. This is useful in | |||||
* cases when the rectangle has been rotated (left, right or bottom up) and | |||||
* later operations need to know the top points. | |||||
* | |||||
* @param {object} An axis-aligned rectangle defined by two points | |||||
* (x1, y1), (x2, y2) and height. | |||||
* @return {object} A rectangle: two points (x1, y1), (x2, y2) and height. | |||||
*/ | |||||
axisAlignedTopPoints: function(r) { | |||||
// Basic | |||||
if (r.y1 === r.y2 && r.x1 < r.x2) | |||||
return r; | |||||
// Rotated to right | |||||
if (r.x1 === r.x2 && r.y2 > r.y1) | |||||
return { | |||||
x1: r.x1 - r.height, y1: r.y1, | |||||
x2: r.x1, y2: r.y1, | |||||
height: r.height | |||||
}; | |||||
// Rotated to left | |||||
if (r.x1 === r.x2 && r.y2 < r.y1) | |||||
return { | |||||
x1: r.x1, y1: r.y2, | |||||
x2: r.x2 + r.height, y2: r.y2, | |||||
height: r.height | |||||
}; | |||||
// Bottom's up | |||||
return { | |||||
x1: r.x2, y1: r.y1 - r.height, | |||||
x2: r.x1, y2: r.y1 - r.height, | |||||
height: r.height | |||||
}; | |||||
}, | |||||
/** | |||||
* Get coordinates of a rectangle's lower left corner from its top points. | |||||
* | |||||
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). | |||||
* @return {object} Coordinates of the corner (x, y). | |||||
*/ | |||||
lowerLeftCoor: function(r) { | |||||
var width = ( | |||||
Math.sqrt( | |||||
Math.pow(r.x2 - r.x1, 2) + | |||||
Math.pow(r.y2 - r.y1, 2) | |||||
) | |||||
); | |||||
return { | |||||
x: r.x1 - (r.y2 - r.y1) * r.height / width, | |||||
y: r.y1 + (r.x2 - r.x1) * r.height / width | |||||
}; | |||||
}, | |||||
/** | |||||
* Get coordinates of a rectangle's lower right corner from its top points | |||||
* and its lower left corner. | |||||
* | |||||
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). | |||||
* @param {object} A corner's coordinates (x, y). | |||||
* @return {object} Coordinates of the corner (x, y). | |||||
*/ | |||||
lowerRightCoor: function(r, llc) { | |||||
return { | |||||
x: llc.x - r.x1 + r.x2, | |||||
y: llc.y - r.y1 + r.y2 | |||||
}; | |||||
}, | |||||
/** | |||||
* Get the coordinates of all the corners of a rectangle from its top point. | |||||
* | |||||
* @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). | |||||
* @return {array} An array of the four corners' coordinates (x, y). | |||||
*/ | |||||
rectangleCorners: function(r) { | |||||
var llc = this.lowerLeftCoor(r), | |||||
lrc = this.lowerRightCoor(r, llc); | |||||
return [ | |||||
{x: r.x1, y: r.y1}, | |||||
{x: r.x2, y: r.y2}, | |||||
{x: llc.x, y: llc.y}, | |||||
{x: lrc.x, y: lrc.y} | |||||
]; | |||||
}, | |||||
/** | |||||
* Split a square defined by its boundaries into four. | |||||
* | |||||
* @param {object} Boundaries of the square (x, y, width, height). | |||||
* @return {array} An array containing the four new squares, themselves | |||||
* defined by an array of their four corners (x, y). | |||||
*/ | |||||
splitSquare: function(b) { | |||||
return [ | |||||
[ | |||||
{x: b.x, y: b.y}, | |||||
{x: b.x + b.width / 2, y: b.y}, | |||||
{x: b.x, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2} | |||||
], | |||||
[ | |||||
{x: b.x + b.width / 2, y: b.y}, | |||||
{x: b.x + b.width, y: b.y}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width, y: b.y + b.height / 2} | |||||
], | |||||
[ | |||||
{x: b.x, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2}, | |||||
{x: b.x, y: b.y + b.height}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height} | |||||
], | |||||
[ | |||||
{x: b.x + b.width / 2, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width, y: b.y + b.height / 2}, | |||||
{x: b.x + b.width / 2, y: b.y + b.height}, | |||||
{x: b.x + b.width, y: b.y + b.height} | |||||
] | |||||
]; | |||||
}, | |||||
/** | |||||
* Compute the four axis between corners of rectangle A and corners of | |||||
* rectangle B. This is needed later to check an eventual collision. | |||||
* | |||||
* @param {array} An array of rectangle A's four corners (x, y). | |||||
* @param {array} An array of rectangle B's four corners (x, y). | |||||
* @return {array} An array of four axis defined by their coordinates (x,y). | |||||
*/ | |||||
axis: function(c1, c2) { | |||||
return [ | |||||
{x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y}, | |||||
{x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y}, | |||||
{x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y}, | |||||
{x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y} | |||||
]; | |||||
}, | |||||
/** | |||||
* Project a rectangle's corner on an axis. | |||||
* | |||||
* @param {object} Coordinates of a corner (x, y). | |||||
* @param {object} Coordinates of an axis (x, y). | |||||
* @return {object} The projection defined by coordinates (x, y). | |||||
*/ | |||||
projection: function(c, a) { | |||||
var l = ( | |||||
(c.x * a.x + c.y * a.y) / | |||||
(Math.pow(a.x, 2) + Math.pow(a.y, 2)) | |||||
); | |||||
return { | |||||
x: l * a.x, | |||||
y: l * a.y | |||||
}; | |||||
}, | |||||
/** | |||||
* Check whether two rectangles collide on one particular axis. | |||||
* | |||||
* @param {object} An axis' coordinates (x, y). | |||||
* @param {array} Rectangle A's corners. | |||||
* @param {array} Rectangle B's corners. | |||||
* @return {boolean} True if the rectangles collide on the axis. | |||||
*/ | |||||
axisCollision: function(a, c1, c2) { | |||||
var sc1 = [], | |||||
sc2 = []; | |||||
for (var ci = 0; ci < 4; ci++) { | |||||
var p1 = this.projection(c1[ci], a), | |||||
p2 = this.projection(c2[ci], a); | |||||
sc1.push(p1.x * a.x + p1.y * a.y); | |||||
sc2.push(p2.x * a.x + p2.y * a.y); | |||||
} | |||||
var maxc1 = Math.max.apply(Math, sc1), | |||||
maxc2 = Math.max.apply(Math, sc2), | |||||
minc1 = Math.min.apply(Math, sc1), | |||||
minc2 = Math.min.apply(Math, sc2); | |||||
return (minc2 <= maxc1 && maxc2 >= minc1); | |||||
}, | |||||
/** | |||||
* Check whether two rectangles collide on each one of their four axis. If | |||||
* all axis collide, then the two rectangles do collide on the plane. | |||||
* | |||||
* @param {array} Rectangle A's corners. | |||||
* @param {array} Rectangle B's corners. | |||||
* @return {boolean} True if the rectangles collide. | |||||
*/ | |||||
collision: function(c1, c2) { | |||||
var axis = this.axis(c1, c2), | |||||
col = true; | |||||
for (var i = 0; i < 4; i++) | |||||
col = col && this.axisCollision(axis[i], c1, c2); | |||||
return col; | |||||
} | |||||
}; | |||||
/** | |||||
* Quad Functions | |||||
* ------------ | |||||
* | |||||
* The Quadtree functions themselves. | |||||
* For each of those functions, we consider that in a splitted quad, the | |||||
* index of each node is the following: | |||||
* 0: top left | |||||
* 1: top right | |||||
* 2: bottom left | |||||
* 3: bottom right | |||||
* | |||||
* Moreover, the hereafter quad's philosophy is to consider that if an element | |||||
* collides with more than one nodes, this element belongs to each of the | |||||
* nodes it collides with where other would let it lie on a higher node. | |||||
*/ | |||||
/** | |||||
* Get the index of the node containing the point in the quad | |||||
* | |||||
* @param {object} point A point defined by coordinates (x, y). | |||||
* @param {object} quadBounds Boundaries of the quad (x, y, width, heigth). | |||||
* @return {integer} The index of the node containing the point. | |||||
*/ | |||||
function _quadIndex(point, quadBounds) { | |||||
var xmp = quadBounds.x + quadBounds.width / 2, | |||||
ymp = quadBounds.y + quadBounds.height / 2, | |||||
top = (point.y < ymp), | |||||
left = (point.x < xmp); | |||||
if (top) { | |||||
if (left) | |||||
return 0; | |||||
else | |||||
return 1; | |||||
} | |||||
else { | |||||
if (left) | |||||
return 2; | |||||
else | |||||
return 3; | |||||
} | |||||
} | |||||
/** | |||||
* Get a list of indexes of nodes containing an axis-aligned rectangle | |||||
* | |||||
* @param {object} rectangle A rectangle defined by two points (x1, y1), | |||||
* (x2, y2) and height. | |||||
* @param {array} quadCorners An array of the quad nodes' corners. | |||||
* @return {array} An array of indexes containing one to | |||||
* four integers. | |||||
*/ | |||||
function _quadIndexes(rectangle, quadCorners) { | |||||
var indexes = []; | |||||
// Iterating through quads | |||||
for (var i = 0; i < 4; i++) | |||||
if ((rectangle.x2 >= quadCorners[i][0].x) && | |||||
(rectangle.x1 <= quadCorners[i][1].x) && | |||||
(rectangle.y1 + rectangle.height >= quadCorners[i][0].y) && | |||||
(rectangle.y1 <= quadCorners[i][2].y)) | |||||
indexes.push(i); | |||||
return indexes; | |||||
} | |||||
/** | |||||
* Get a list of indexes of nodes containing a non-axis-aligned rectangle | |||||
* | |||||
* @param {array} corners An array containing each corner of the | |||||
* rectangle defined by its coordinates (x, y). | |||||
* @param {array} quadCorners An array of the quad nodes' corners. | |||||
* @return {array} An array of indexes containing one to | |||||
* four integers. | |||||
*/ | |||||
function _quadCollision(corners, quadCorners) { | |||||
var indexes = []; | |||||
// Iterating through quads | |||||
for (var i = 0; i < 4; i++) | |||||
if (_geom.collision(corners, quadCorners[i])) | |||||
indexes.push(i); | |||||
return indexes; | |||||
} | |||||
/** | |||||
* Subdivide a quad by creating a node at a precise index. The function does | |||||
* not generate all four nodes not to potentially create unused nodes. | |||||
* | |||||
* @param {integer} index The index of the node to create. | |||||
* @param {object} quad The quad object to subdivide. | |||||
* @return {object} A new quad representing the node created. | |||||
*/ | |||||
function _quadSubdivide(index, quad) { | |||||
var next = quad.level + 1, | |||||
subw = Math.round(quad.bounds.width / 2), | |||||
subh = Math.round(quad.bounds.height / 2), | |||||
qx = Math.round(quad.bounds.x), | |||||
qy = Math.round(quad.bounds.y), | |||||
x, | |||||
y; | |||||
switch (index) { | |||||
case 0: | |||||
x = qx; | |||||
y = qy; | |||||
break; | |||||
case 1: | |||||
x = qx + subw; | |||||
y = qy; | |||||
break; | |||||
case 2: | |||||
x = qx; | |||||
y = qy + subh; | |||||
break; | |||||
case 3: | |||||
x = qx + subw; | |||||
y = qy + subh; | |||||
break; | |||||
} | |||||
return _quadTree( | |||||
{x: x, y: y, width: subw, height: subh}, | |||||
next, | |||||
quad.maxElements, | |||||
quad.maxLevel | |||||
); | |||||
} | |||||
/** | |||||
* Recursively insert an element into the quadtree. Only points | |||||
* with size, i.e. axis-aligned squares, may be inserted with this | |||||
* method. | |||||
* | |||||
* @param {object} el The element to insert in the quadtree. | |||||
* @param {object} sizedPoint A sized point defined by two top points | |||||
* (x1, y1), (x2, y2) and height. | |||||
* @param {object} quad The quad in which to insert the element. | |||||
* @return {undefined} The function does not return anything. | |||||
*/ | |||||
function _quadInsert(el, sizedPoint, quad) { | |||||
if (quad.level < quad.maxLevel) { | |||||
// Searching appropriate quads | |||||
var indexes = _quadIndexes(sizedPoint, quad.corners); | |||||
// Iterating | |||||
for (var i = 0, l = indexes.length; i < l; i++) { | |||||
// Subdividing if necessary | |||||
if (quad.nodes[indexes[i]] === undefined) | |||||
quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad); | |||||
// Recursion | |||||
_quadInsert(el, sizedPoint, quad.nodes[indexes[i]]); | |||||
} | |||||
} | |||||
else { | |||||
// Pushing the element in a leaf node | |||||
quad.elements.push(el); | |||||
} | |||||
} | |||||
/** | |||||
* Recursively retrieve every elements held by the node containing the | |||||
* searched point. | |||||
* | |||||
* @param {object} point The searched point (x, y). | |||||
* @param {object} quad The searched quad. | |||||
* @return {array} An array of elements contained in the relevant | |||||
* node. | |||||
*/ | |||||
function _quadRetrievePoint(point, quad) { | |||||
if (quad.level < quad.maxLevel) { | |||||
var index = _quadIndex(point, quad.bounds); | |||||
// If node does not exist we return an empty list | |||||
if (quad.nodes[index] !== undefined) { | |||||
return _quadRetrievePoint(point, quad.nodes[index]); | |||||
} | |||||
else { | |||||
return []; | |||||
} | |||||
} | |||||
else { | |||||
return quad.elements; | |||||
} | |||||
} | |||||
/** | |||||
* Recursively retrieve every elements contained within an rectangular area | |||||
* that may or may not be axis-aligned. | |||||
* | |||||
* @param {object|array} rectData The searched area defined either by | |||||
* an array of four corners (x, y) in | |||||
* the case of a non-axis-aligned | |||||
* rectangle or an object with two top | |||||
* points (x1, y1), (x2, y2) and height. | |||||
* @param {object} quad The searched quad. | |||||
* @param {function} collisionFunc The collision function used to search | |||||
* for node indexes. | |||||
* @param {array?} els The retrieved elements. | |||||
* @return {array} An array of elements contained in the | |||||
* area. | |||||
*/ | |||||
function _quadRetrieveArea(rectData, quad, collisionFunc, els) { | |||||
els = els || {}; | |||||
if (quad.level < quad.maxLevel) { | |||||
var indexes = collisionFunc(rectData, quad.corners); | |||||
for (var i = 0, l = indexes.length; i < l; i++) | |||||
if (quad.nodes[indexes[i]] !== undefined) | |||||
_quadRetrieveArea( | |||||
rectData, | |||||
quad.nodes[indexes[i]], | |||||
collisionFunc, | |||||
els | |||||
); | |||||
} else | |||||
for (var j = 0, m = quad.elements.length; j < m; j++) | |||||
if (els[quad.elements[j].id] === undefined) | |||||
els[quad.elements[j].id] = quad.elements[j]; | |||||
return els; | |||||
} | |||||
/** | |||||
* Creates the quadtree object itself. | |||||
* | |||||
* @param {object} bounds The boundaries of the quad defined by an | |||||
* origin (x, y), width and heigth. | |||||
* @param {integer} level The level of the quad in the tree. | |||||
* @param {integer} maxElements The max number of element in a leaf node. | |||||
* @param {integer} maxLevel The max recursion level of the tree. | |||||
* @return {object} The quadtree object. | |||||
*/ | |||||
function _quadTree(bounds, level, maxElements, maxLevel) { | |||||
return { | |||||
level: level || 0, | |||||
bounds: bounds, | |||||
corners: _geom.splitSquare(bounds), | |||||
maxElements: maxElements || 20, | |||||
maxLevel: maxLevel || 4, | |||||
elements: [], | |||||
nodes: [] | |||||
}; | |||||
} | |||||
/** | |||||
* Sigma Quad Constructor | |||||
* ---------------------- | |||||
* | |||||
* The quad API as exposed to sigma. | |||||
*/ | |||||
/** | |||||
* The quad core that will become the sigma interface with the quadtree. | |||||
* | |||||
* property {object} _tree Property holding the quadtree object. | |||||
* property {object} _geom Exposition of the _geom namespace for testing. | |||||
* property {object} _cache Cache for the area method. | |||||
*/ | |||||
var quad = function() { | |||||
this._geom = _geom; | |||||
this._tree = null; | |||||
this._cache = { | |||||
query: false, | |||||
result: false | |||||
}; | |||||
}; | |||||
/** | |||||
* Index a graph by inserting its nodes into the quadtree. | |||||
* | |||||
* @param {array} nodes An array of nodes to index. | |||||
* @param {object} params An object of parameters with at least the quad | |||||
* bounds. | |||||
* @return {object} The quadtree object. | |||||
* | |||||
* Parameters: | |||||
* ---------- | |||||
* bounds: {object} boundaries of the quad defined by its origin (x, y) | |||||
* width and heigth. | |||||
* prefix: {string?} a prefix for node geometric attributes. | |||||
* maxElements: {integer?} the max number of elements in a leaf node. | |||||
* maxLevel: {integer?} the max recursion level of the tree. | |||||
*/ | |||||
quad.prototype.index = function(nodes, params) { | |||||
// Enforcing presence of boundaries | |||||
if (!params.bounds) | |||||
throw 'sigma.classes.quad.index: bounds information not given.'; | |||||
// Prefix | |||||
var prefix = params.prefix || ''; | |||||
// Building the tree | |||||
this._tree = _quadTree( | |||||
params.bounds, | |||||
0, | |||||
params.maxElements, | |||||
params.maxLevel | |||||
); | |||||
// Inserting graph nodes into the tree | |||||
for (var i = 0, l = nodes.length; i < l; i++) { | |||||
// Inserting node | |||||
_quadInsert( | |||||
nodes[i], | |||||
_geom.pointToSquare({ | |||||
x: nodes[i][prefix + 'x'], | |||||
y: nodes[i][prefix + 'y'], | |||||
size: nodes[i][prefix + 'size'] | |||||
}), | |||||
this._tree | |||||
); | |||||
} | |||||
// Reset cache: | |||||
this._cache = { | |||||
query: false, | |||||
result: false | |||||
}; | |||||
// remove? | |||||
return this._tree; | |||||
}; | |||||
/** | |||||
* Retrieve every graph nodes held by the quadtree node containing the | |||||
* searched point. | |||||
* | |||||
* @param {number} x of the point. | |||||
* @param {number} y of the point. | |||||
* @return {array} An array of nodes retrieved. | |||||
*/ | |||||
quad.prototype.point = function(x, y) { | |||||
return this._tree ? | |||||
_quadRetrievePoint({x: x, y: y}, this._tree) || [] : | |||||
[]; | |||||
}; | |||||
/** | |||||
* Retrieve every graph nodes within a rectangular area. The methods keep the | |||||
* last area queried in cache for optimization reason and will act differently | |||||
* for the same reason if the area is axis-aligned or not. | |||||
* | |||||
* @param {object} A rectangle defined by two top points (x1, y1), (x2, y2) | |||||
* and height. | |||||
* @return {array} An array of nodes retrieved. | |||||
*/ | |||||
quad.prototype.area = function(rect) { | |||||
var serialized = JSON.stringify(rect), | |||||
collisionFunc, | |||||
rectData; | |||||
// Returning cache? | |||||
if (this._cache.query === serialized) | |||||
return this._cache.result; | |||||
// Axis aligned ? | |||||
if (_geom.isAxisAligned(rect)) { | |||||
collisionFunc = _quadIndexes; | |||||
rectData = _geom.axisAlignedTopPoints(rect); | |||||
} | |||||
else { | |||||
collisionFunc = _quadCollision; | |||||
rectData = _geom.rectangleCorners(rect); | |||||
} | |||||
// Retrieving nodes | |||||
var nodes = this._tree ? | |||||
_quadRetrieveArea( | |||||
rectData, | |||||
this._tree, | |||||
collisionFunc | |||||
) : | |||||
[]; | |||||
// Object to array | |||||
var nodesArray = []; | |||||
for (var i in nodes) | |||||
nodesArray.push(nodes[i]); | |||||
// Caching | |||||
this._cache.query = serialized; | |||||
this._cache.result = nodesArray; | |||||
return nodesArray; | |||||
}; | |||||
/** | |||||
* EXPORT: | |||||
* ******* | |||||
*/ | |||||
if (typeof this.sigma !== 'undefined') { | |||||
this.sigma.classes = this.sigma.classes || {}; | |||||
this.sigma.classes.quad = quad; | |||||
} else if (typeof exports !== 'undefined') { | |||||
if (typeof module !== 'undefined' && module.exports) | |||||
exports = module.exports = quad; | |||||
exports.quad = quad; | |||||
} else | |||||
this.quad = quad; | |||||
}).call(this); |
@ -0,0 +1,984 @@ | |||||
/** | |||||
* conrad.js is a tiny JavaScript jobs scheduler, | |||||
* | |||||
* Version: 0.1.0 | |||||
* Sources: http://github.com/jacomyal/conrad.js | |||||
* Doc: http://github.com/jacomyal/conrad.js#readme | |||||
* | |||||
* License: | |||||
* -------- | |||||
* Copyright © 2013 Alexis Jacomy, Sciences-Po médialab | |||||
* | |||||
* Permission is hereby granted, free of charge, to any person obtaining a copy | |||||
* of this software and associated documentation files (the "Software"), to | |||||
* deal in the Software without restriction, including without limitation the | |||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | |||||
* sell copies of the Software, and to permit persons to whom the Software is | |||||
* furnished to do so, subject to the following conditions: | |||||
* | |||||
* The above copyright notice and this permission notice shall be included in | |||||
* all copies or substantial portions of the Software. | |||||
* | |||||
* The Software is provided "as is", without warranty of any kind, express or | |||||
* implied, including but not limited to the warranties of merchantability, | |||||
* fitness for a particular purpose and noninfringement. In no event shall the | |||||
* authors or copyright holders be liable for any claim, damages or other | |||||
* liability, whether in an action of contract, tort or otherwise, arising | |||||
* from, out of or in connection with the software or the use or other dealings | |||||
* in the Software. | |||||
*/ | |||||
(function(global) { | |||||
'use strict'; | |||||
// Check that conrad.js has not been loaded yet: | |||||
if (global.conrad) | |||||
throw new Error('conrad already exists'); | |||||
/** | |||||
* PRIVATE VARIABLES: | |||||
* ****************** | |||||
*/ | |||||
/** | |||||
* A flag indicating whether conrad is running or not. | |||||
* | |||||
* @type {Number} | |||||
*/ | |||||
var _lastFrameTime; | |||||
/** | |||||
* A flag indicating whether conrad is running or not. | |||||
* | |||||
* @type {Boolean} | |||||
*/ | |||||
var _isRunning = false; | |||||
/** | |||||
* The hash of registered jobs. Each job must at least have a unique ID | |||||
* under the key "id" and a function under the key "job". This hash | |||||
* contains each running job and each waiting job. | |||||
* | |||||
* @type {Object} | |||||
*/ | |||||
var _jobs = {}; | |||||
/** | |||||
* The hash of currently running jobs. | |||||
* | |||||
* @type {Object} | |||||
*/ | |||||
var _runningJobs = {}; | |||||
/** | |||||
* The array of currently running jobs, sorted by priority. | |||||
* | |||||
* @type {Array} | |||||
*/ | |||||
var _sortedByPriorityJobs = []; | |||||
/** | |||||
* The array of currently waiting jobs. | |||||
* | |||||
* @type {Object} | |||||
*/ | |||||
var _waitingJobs = {}; | |||||
/** | |||||
* The array of finished jobs. They are stored in an array, since two jobs | |||||
* with the same "id" can happen at two different times. | |||||
* | |||||
* @type {Array} | |||||
*/ | |||||
var _doneJobs = []; | |||||
/** | |||||
* A dirty flag to keep conrad from starting: Indeed, when addJob() is called | |||||
* with several jobs, conrad must be started only at the end. This flag keeps | |||||
* me from duplicating the code that effectively adds a job. | |||||
* | |||||
* @type {Boolean} | |||||
*/ | |||||
var _noStart = false; | |||||
/** | |||||
* An hash containing some global settings about how conrad.js should | |||||
* behave. | |||||
* | |||||
* @type {Object} | |||||
*/ | |||||
var _parameters = { | |||||
frameDuration: 20, | |||||
history: true | |||||
}; | |||||
/** | |||||
* This object contains every handlers bound to conrad events. It does not | |||||
* requirea any DOM implementation, since the events are all JavaScript. | |||||
* | |||||
* @type {Object} | |||||
*/ | |||||
var _handlers = Object.create(null); | |||||
/** | |||||
* PRIVATE FUNCTIONS: | |||||
* ****************** | |||||
*/ | |||||
/** | |||||
* Will execute the handler everytime that the indicated event (or the | |||||
* indicated events) will be triggered. | |||||
* | |||||
* @param {string|array|object} events The name of the event (or the events | |||||
* separated by spaces). | |||||
* @param {function(Object)} handler The handler to bind. | |||||
* @return {Object} Returns conrad. | |||||
*/ | |||||
function _bind(events, handler) { | |||||
var i, | |||||
i_end, | |||||
event, | |||||
eArray; | |||||
if (!arguments.length) | |||||
return; | |||||
else if ( | |||||
arguments.length === 1 && | |||||
Object(arguments[0]) === arguments[0] | |||||
) | |||||
for (events in arguments[0]) | |||||
_bind(events, arguments[0][events]); | |||||
else if (arguments.length > 1) { | |||||
eArray = | |||||
Array.isArray(events) ? | |||||
events : | |||||
events.split(/ /); | |||||
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { | |||||
event = eArray[i]; | |||||
if (!_handlers[event]) | |||||
_handlers[event] = []; | |||||
// Using an object instead of directly the handler will make possible | |||||
// later to add flags | |||||
_handlers[event].push({ | |||||
handler: handler | |||||
}); | |||||
} | |||||
} | |||||
} | |||||
/** | |||||
* Removes the handler from a specified event (or specified events). | |||||
* | |||||
* @param {?string} events The name of the event (or the events | |||||
* separated by spaces). If undefined, | |||||
* then all handlers are removed. | |||||
* @param {?function(Object)} handler The handler to unbind. If undefined, | |||||
* each handler bound to the event or the | |||||
* events will be removed. | |||||
* @return {Object} Returns conrad. | |||||
*/ | |||||
function _unbind(events, handler) { | |||||
var i, | |||||
i_end, | |||||
j, | |||||
j_end, | |||||
a, | |||||
event, | |||||
eArray = Array.isArray(events) ? | |||||
events : | |||||
events.split(/ /); | |||||
if (!arguments.length) | |||||
_handlers = Object.create(null); | |||||
else if (handler) { | |||||
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { | |||||
event = eArray[i]; | |||||
if (_handlers[event]) { | |||||
a = []; | |||||
for (j = 0, j_end = _handlers[event].length; j !== j_end; j += 1) | |||||
if (_handlers[event][j].handler !== handler) | |||||
a.push(_handlers[event][j]); | |||||
_handlers[event] = a; | |||||
} | |||||
if (_handlers[event] && _handlers[event].length === 0) | |||||
delete _handlers[event]; | |||||
} | |||||
} else | |||||
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) | |||||
delete _handlers[eArray[i]]; | |||||
} | |||||
/** | |||||
* Executes each handler bound to the event. | |||||
* | |||||
* @param {string} events The name of the event (or the events separated | |||||
* by spaces). | |||||
* @param {?Object} data The content of the event (optional). | |||||
* @return {Object} Returns conrad. | |||||
*/ | |||||
function _dispatch(events, data) { | |||||
var i, | |||||
j, | |||||
i_end, | |||||
j_end, | |||||
event, | |||||
eventName, | |||||
eArray = Array.isArray(events) ? | |||||
events : | |||||
events.split(/ /); | |||||
data = data === undefined ? {} : data; | |||||
for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { | |||||
eventName = eArray[i]; | |||||
if (_handlers[eventName]) { | |||||
event = { | |||||
type: eventName, | |||||
data: data || {} | |||||
}; | |||||
for (j = 0, j_end = _handlers[eventName].length; j !== j_end; j += 1) | |||||
try { | |||||
_handlers[eventName][j].handler(event); | |||||
} catch (e) {} | |||||
} | |||||
} | |||||
} | |||||
/** | |||||
* Executes the most prioritary job once, and deals with filling the stats | |||||
* (done, time, averageTime, currentTime, etc...). | |||||
* | |||||
* @return {?Object} Returns the job object if it has to be killed, null else. | |||||
*/ | |||||
function _executeFirstJob() { | |||||
var i, | |||||
l, | |||||
test, | |||||
kill, | |||||
pushed = false, | |||||
time = __dateNow(), | |||||
job = _sortedByPriorityJobs.shift(); | |||||
// Execute the job and look at the result: | |||||
test = job.job(); | |||||
// Deal with stats: | |||||
time = __dateNow() - time; | |||||
job.done++; | |||||
job.time += time; | |||||
job.currentTime += time; | |||||
job.weightTime = job.currentTime / (job.weight || 1); | |||||
job.averageTime = job.time / job.done; | |||||
// Check if the job has to be killed: | |||||
kill = job.count ? (job.count <= job.done) : !test; | |||||
// Reset priorities: | |||||
if (!kill) { | |||||
for (i = 0, l = _sortedByPriorityJobs.length; i < l; i++) | |||||
if (_sortedByPriorityJobs[i].weightTime > job.weightTime) { | |||||
_sortedByPriorityJobs.splice(i, 0, job); | |||||
pushed = true; | |||||
break; | |||||
} | |||||
if (!pushed) | |||||
_sortedByPriorityJobs.push(job); | |||||
} | |||||
return kill ? job : null; | |||||
} | |||||
/** | |||||
* Activates a job, by adding it to the _runningJobs object and the | |||||
* _sortedByPriorityJobs array. It also initializes its currentTime value. | |||||
* | |||||
* @param {Object} job The job to activate. | |||||
*/ | |||||
function _activateJob(job) { | |||||
var l = _sortedByPriorityJobs.length; | |||||
// Add the job to the running jobs: | |||||
_runningJobs[job.id] = job; | |||||
job.status = 'running'; | |||||
// Add the job to the priorities: | |||||
if (l) { | |||||
job.weightTime = _sortedByPriorityJobs[l - 1].weightTime; | |||||
job.currentTime = job.weightTime * (job.weight || 1); | |||||
} | |||||
// Initialize the job and dispatch: | |||||
job.startTime = __dateNow(); | |||||
_dispatch('jobStarted', __clone(job)); | |||||
_sortedByPriorityJobs.push(job); | |||||
} | |||||
/** | |||||
* The main loop of conrad.js: | |||||
* . It executes job such that they all occupate the same processing time. | |||||
* . It stops jobs that do not need to be executed anymore. | |||||
* . It triggers callbacks when it is relevant. | |||||
* . It starts waiting jobs when they need to be started. | |||||
* . It injects frames to keep a constant frapes per second ratio. | |||||
* . It stops itself when there are no more jobs to execute. | |||||
*/ | |||||
function _loop() { | |||||
var k, | |||||
o, | |||||
l, | |||||
job, | |||||
time, | |||||
deadJob; | |||||
// Deal with the newly added jobs (the _jobs object): | |||||
for (k in _jobs) { | |||||
job = _jobs[k]; | |||||
if (job.after) | |||||
_waitingJobs[k] = job; | |||||
else | |||||
_activateJob(job); | |||||
delete _jobs[k]; | |||||
} | |||||
// Set the _isRunning flag to false if there are no running job: | |||||
_isRunning = !!_sortedByPriorityJobs.length; | |||||
// Deal with the running jobs (the _runningJobs object): | |||||
while ( | |||||
_sortedByPriorityJobs.length && | |||||
__dateNow() - _lastFrameTime < _parameters.frameDuration | |||||
) { | |||||
deadJob = _executeFirstJob(); | |||||
// Deal with the case where the job has ended: | |||||
if (deadJob) { | |||||
_killJob(deadJob.id); | |||||
// Check for waiting jobs: | |||||
for (k in _waitingJobs) | |||||
if (_waitingJobs[k].after === deadJob.id) { | |||||
_activateJob(_waitingJobs[k]); | |||||
delete _waitingJobs[k]; | |||||
} | |||||
} | |||||
} | |||||
// Check if conrad still has jobs to deal with, and kill it if not: | |||||
if (_isRunning) { | |||||
// Update the _lastFrameTime: | |||||
_lastFrameTime = __dateNow(); | |||||
_dispatch('enterFrame'); | |||||
setTimeout(_loop, 0); | |||||
} else | |||||
_dispatch('stop'); | |||||
} | |||||
/** | |||||
* Adds one or more jobs, and starts the loop if no job was running before. A | |||||
* job is at least a unique string "id" and a function, and there are some | |||||
* parameters that you can specify for each job to modify the way conrad will | |||||
* execute it. If a job is added with the "id" of another job that is waiting | |||||
* or still running, an error will be thrown. | |||||
* | |||||
* When a job is added, it is referenced in the _jobs object, by its id. | |||||
* Then, if it has to be executed right now, it will be also referenced in | |||||
* the _runningJobs object. If it has to wait, then it will be added into the | |||||
* _waitingJobs object, until it can start. | |||||
* | |||||
* Keep reading this documentation to see how to call this method. | |||||
* | |||||
* @return {Object} Returns conrad. | |||||
* | |||||
* Adding one job: | |||||
* *************** | |||||
* Basically, a job is defined by its string id and a function (the job). It | |||||
* is also possible to add some parameters: | |||||
* | |||||
* > conrad.addJob('myJobId', myJobFunction); | |||||
* > conrad.addJob('myJobId', { | |||||
* > job: myJobFunction, | |||||
* > someParameter: someValue | |||||
* > }); | |||||
* > conrad.addJob({ | |||||
* > id: 'myJobId', | |||||
* > job: myJobFunction, | |||||
* > someParameter: someValue | |||||
* > }); | |||||
* | |||||
* Adding several jobs: | |||||
* ******************** | |||||
* When adding several jobs at the same time, it is possible to specify | |||||
* parameters for each one individually or for all: | |||||
* | |||||
* > conrad.addJob([ | |||||
* > { | |||||
* > id: 'myJobId1', | |||||
* > job: myJobFunction1, | |||||
* > someParameter1: someValue1 | |||||
* > }, | |||||
* > { | |||||
* > id: 'myJobId2', | |||||
* > job: myJobFunction2, | |||||
* > someParameter2: someValue2 | |||||
* > } | |||||
* > ], { | |||||
* > someCommonParameter: someCommonValue | |||||
* > }); | |||||
* > conrad.addJob({ | |||||
* > myJobId1: {, | |||||
* > job: myJobFunction1, | |||||
* > someParameter1: someValue1 | |||||
* > }, | |||||
* > myJobId2: {, | |||||
* > job: myJobFunction2, | |||||
* > someParameter2: someValue2 | |||||
* > } | |||||
* > }, { | |||||
* > someCommonParameter: someCommonValue | |||||
* > }); | |||||
* > conrad.addJob({ | |||||
* > myJobId1: myJobFunction1, | |||||
* > myJobId2: myJobFunction2 | |||||
* > }, { | |||||
* > someCommonParameter: someCommonValue | |||||
* > }); | |||||
* | |||||
* Recognized parameters: | |||||
* ********************** | |||||
* Here is the exhaustive list of every accepted parameters: | |||||
* | |||||
* {?Function} end A callback to execute when the job is ended. It is | |||||
* not executed if the job is killed instead of ended | |||||
* "naturally". | |||||
* {?Integer} count The number of time the job has to be executed. | |||||
* {?Number} weight If specified, the job will be executed as it was | |||||
* added "weight" times. | |||||
* {?String} after The id of another job (eventually not added yet). | |||||
* If specified, this job will start only when the | |||||
* specified "after" job is ended. | |||||
*/ | |||||
function _addJob(v1, v2) { | |||||
var i, | |||||
l, | |||||
o; | |||||
// Array of jobs: | |||||
if (Array.isArray(v1)) { | |||||
// Keep conrad to start until the last job is added: | |||||
_noStart = true; | |||||
for (i = 0, l = v1.length; i < l; i++) | |||||
_addJob(v1[i].id, __extend(v1[i], v2)); | |||||
_noStart = false; | |||||
if (!_isRunning) { | |||||
// Update the _lastFrameTime: | |||||
_lastFrameTime = __dateNow(); | |||||
_dispatch('start'); | |||||
_loop(); | |||||
} | |||||
} else if (typeof v1 === 'object') { | |||||
// One job (object): | |||||
if (typeof v1.id === 'string') | |||||
_addJob(v1.id, v1); | |||||
// Hash of jobs: | |||||
else { | |||||
// Keep conrad to start until the last job is added: | |||||
_noStart = true; | |||||
for (i in v1) | |||||
if (typeof v1[i] === 'function') | |||||
_addJob(i, __extend({ | |||||
job: v1[i] | |||||
}, v2)); | |||||
else | |||||
_addJob(i, __extend(v1[i], v2)); | |||||
_noStart = false; | |||||
if (!_isRunning) { | |||||
// Update the _lastFrameTime: | |||||
_lastFrameTime = __dateNow(); | |||||
_dispatch('start'); | |||||
_loop(); | |||||
} | |||||
} | |||||
// One job (string, *): | |||||
} else if (typeof v1 === 'string') { | |||||
if (_hasJob(v1)) | |||||
throw new Error( | |||||
'[conrad.addJob] Job with id "' + v1 + '" already exists.' | |||||
); | |||||
// One job (string, function): | |||||
if (typeof v2 === 'function') { | |||||
o = { | |||||
id: v1, | |||||
done: 0, | |||||
time: 0, | |||||
status: 'waiting', | |||||
currentTime: 0, | |||||
averageTime: 0, | |||||
weightTime: 0, | |||||
job: v2 | |||||
}; | |||||
// One job (string, object): | |||||
} else if (typeof v2 === 'object') { | |||||
o = __extend( | |||||
{ | |||||
id: v1, | |||||
done: 0, | |||||
time: 0, | |||||
status: 'waiting', | |||||
currentTime: 0, | |||||
averageTime: 0, | |||||
weightTime: 0 | |||||
}, | |||||
v2 | |||||
); | |||||
// If none of those cases, throw an error: | |||||
} else | |||||
throw new Error('[conrad.addJob] Wrong arguments.'); | |||||
// Effectively add the job: | |||||
_jobs[v1] = o; | |||||
_dispatch('jobAdded', __clone(o)); | |||||
// Check if the loop has to be started: | |||||
if (!_isRunning && !_noStart) { | |||||
// Update the _lastFrameTime: | |||||
_lastFrameTime = __dateNow(); | |||||
_dispatch('start'); | |||||
_loop(); | |||||
} | |||||
// If none of those cases, throw an error: | |||||
} else | |||||
throw new Error('[conrad.addJob] Wrong arguments.'); | |||||
return this; | |||||
} | |||||
/** | |||||
* Kills one or more jobs, indicated by their ids. It is only possible to | |||||
* kill running jobs or waiting jobs. If you try to kill a job that does not | |||||
* exist or that is already killed, a warning will be thrown. | |||||
* | |||||
* @param {Array|String} v1 A string job id or an array of job ids. | |||||
* @return {Object} Returns conrad. | |||||
*/ | |||||
function _killJob(v1) { | |||||
var i, | |||||
l, | |||||
k, | |||||
a, | |||||
job, | |||||
found = false; | |||||
// Array of job ids: | |||||
if (Array.isArray(v1)) | |||||
for (i = 0, l = v1.length; i < l; i++) | |||||
_killJob(v1[i]); | |||||
// One job's id: | |||||
else if (typeof v1 === 'string') { | |||||
a = [_runningJobs, _waitingJobs, _jobs]; | |||||
// Remove the job from the hashes: | |||||
for (i = 0, l = a.length; i < l; i++) | |||||
if (v1 in a[i]) { | |||||
job = a[i][v1]; | |||||
if (_parameters.history) { | |||||
job.status = 'done'; | |||||
_doneJobs.push(job); | |||||
} | |||||
_dispatch('jobEnded', __clone(job)); | |||||
delete a[i][v1]; | |||||
if (typeof job.end === 'function') | |||||
job.end(); | |||||
found = true; | |||||
} | |||||
// Remove the priorities array: | |||||
a = _sortedByPriorityJobs; | |||||
for (i = 0, l = a.length; i < l; i++) | |||||
if (a[i].id === v1) { | |||||
a.splice(i, 1); | |||||
break; | |||||
} | |||||
if (!found) | |||||
throw new Error('[conrad.killJob] Job "' + v1 + '" not found.'); | |||||
// If none of those cases, throw an error: | |||||
} else | |||||
throw new Error('[conrad.killJob] Wrong arguments.'); | |||||
return this; | |||||
} | |||||
/** | |||||
* Kills every running, waiting, and just added jobs. | |||||
* | |||||
* @return {Object} Returns conrad. | |||||
*/ | |||||
function _killAll() { | |||||
var k, | |||||
jobs = __extend(_jobs, _runningJobs, _waitingJobs); | |||||
// Take every jobs and push them into the _doneJobs object: | |||||
if (_parameters.history) | |||||
for (k in jobs) { | |||||
jobs[k].status = 'done'; | |||||
_doneJobs.push(jobs[k]); | |||||
if (typeof jobs[k].end === 'function') | |||||
jobs[k].end(); | |||||
} | |||||
// Reinitialize the different jobs lists: | |||||
_jobs = {}; | |||||
_waitingJobs = {}; | |||||
_runningJobs = {}; | |||||
_sortedByPriorityJobs = []; | |||||
// In case some jobs are added right after the kill: | |||||
_isRunning = false; | |||||
return this; | |||||
} | |||||
/** | |||||
* Returns true if a job with the specified id is currently running or | |||||
* waiting, and false else. | |||||
* | |||||
* @param {String} id The id of the job. | |||||
* @return {?Object} Returns the job object if it exists. | |||||
*/ | |||||
function _hasJob(id) { | |||||
var job = _jobs[id] || _runningJobs[id] || _waitingJobs[id]; | |||||
return job ? __extend(job) : null; | |||||
} | |||||
/** | |||||
* This method will set the setting specified by "v1" to the value specified | |||||
* by "v2" if both are given, and else return the current value of the | |||||
* settings "v1". | |||||
* | |||||
* @param {String} v1 The name of the property. | |||||
* @param {?*} v2 Eventually, a value to set to the specified | |||||
* property. | |||||
* @return {Object|*} Returns the specified settings value if "v2" is not | |||||
* given, and conrad else. | |||||
*/ | |||||
function _settings(v1, v2) { | |||||
var o; | |||||
if (typeof a1 === 'string' && arguments.length === 1) | |||||
return _parameters[a1]; | |||||
else { | |||||
o = (typeof a1 === 'object' && arguments.length === 1) ? | |||||
a1 || {} : | |||||
{}; | |||||
if (typeof a1 === 'string') | |||||
o[a1] = a2; | |||||
for (var k in o) | |||||
if (o[k] !== undefined) | |||||
_parameters[k] = o[k]; | |||||
else | |||||
delete _parameters[k]; | |||||
return this; | |||||
} | |||||
} | |||||
/** | |||||
* Returns true if conrad is currently running, and false else. | |||||
* | |||||
* @return {Boolean} Returns _isRunning. | |||||
*/ | |||||
function _getIsRunning() { | |||||
return _isRunning; | |||||
} | |||||
/** | |||||
* Unreference every job that is stored in the _doneJobs object. It will | |||||
* not be possible anymore to get stats about these jobs, but it will release | |||||
* the memory. | |||||
* | |||||
* @return {Object} Returns conrad. | |||||
*/ | |||||
function _clearHistory() { | |||||
_doneJobs = []; | |||||
return this; | |||||
} | |||||
/** | |||||
* Returns a snapshot of every data about jobs that wait to be started, are | |||||
* currently running or are done. | |||||
* | |||||
* It is possible to get only running, waiting or done jobs by giving | |||||
* "running", "waiting" or "done" as fist argument. | |||||
* | |||||
* It is also possible to get every job with a specified id by giving it as | |||||
* first argument. Also, using a RegExp instead of an id will return every | |||||
* jobs whose ids match the RegExp. And these two last use cases work as well | |||||
* by giving before "running", "waiting" or "done". | |||||
* | |||||
* @return {Array} The array of the matching jobs. | |||||
* | |||||
* Some call examples: | |||||
* ******************* | |||||
* > conrad.getStats('running') | |||||
* > conrad.getStats('waiting') | |||||
* > conrad.getStats('done') | |||||
* > conrad.getStats('myJob') | |||||
* > conrad.getStats(/test/) | |||||
* > conrad.getStats('running', 'myRunningJob') | |||||
* > conrad.getStats('running', /test/) | |||||
*/ | |||||
function _getStats(v1, v2) { | |||||
var a, | |||||
k, | |||||
i, | |||||
l, | |||||
stats, | |||||
pattern, | |||||
isPatternString; | |||||
if (!arguments.length) { | |||||
stats = []; | |||||
for (k in _jobs) | |||||
stats.push(_jobs[k]); | |||||
for (k in _waitingJobs) | |||||
stats.push(_waitingJobs[k]); | |||||
for (k in _runningJobs) | |||||
stats.push(_runningJobs[k]); | |||||
stats = stats.concat(_doneJobs); | |||||
} | |||||
if (typeof v1 === 'string') | |||||
switch (v1) { | |||||
case 'waiting': | |||||
stats = __objectValues(_waitingJobs); | |||||
break; | |||||
case 'running': | |||||
stats = __objectValues(_runningJobs); | |||||
break; | |||||
case 'done': | |||||
stats = _doneJobs; | |||||
break; | |||||
default: | |||||
pattern = v1; | |||||
} | |||||
if (v1 instanceof RegExp) | |||||
pattern = v1; | |||||
if (!pattern && (typeof v2 === 'string' || v2 instanceof RegExp)) | |||||
pattern = v2; | |||||
// Filter jobs if a pattern is given: | |||||
if (pattern) { | |||||
isPatternString = typeof pattern === 'string'; | |||||
if (stats instanceof Array) { | |||||
a = stats; | |||||
} else if (typeof stats === 'object') { | |||||
a = []; | |||||
for (k in stats) | |||||
a = a.concat(stats[k]); | |||||
} else { | |||||
a = []; | |||||
for (k in _jobs) | |||||
a.push(_jobs[k]); | |||||
for (k in _waitingJobs) | |||||
a.push(_waitingJobs[k]); | |||||
for (k in _runningJobs) | |||||
a.push(_runningJobs[k]); | |||||
a = a.concat(_doneJobs); | |||||
} | |||||
stats = []; | |||||
for (i = 0, l = a.length; i < l; i++) | |||||
if (isPatternString ? a[i].id === pattern : a[i].id.match(pattern)) | |||||
stats.push(a[i]); | |||||
} | |||||
return __clone(stats); | |||||
} | |||||
/** | |||||
* TOOLS FUNCTIONS: | |||||
* **************** | |||||
*/ | |||||
/** | |||||
* This function takes any number of objects as arguments, copies from each | |||||
* of these objects each pair key/value into a new object, and finally | |||||
* returns this object. | |||||
* | |||||
* The arguments are parsed from the last one to the first one, such that | |||||
* when two objects have keys in common, the "earliest" object wins. | |||||
* | |||||
* Example: | |||||
* ******** | |||||
* > var o1 = { | |||||
* > a: 1, | |||||
* > b: 2, | |||||
* > c: '3' | |||||
* > }, | |||||
* > o2 = { | |||||
* > c: '4', | |||||
* > d: [ 5 ] | |||||
* > }; | |||||
* > __extend(o1, o2); | |||||
* > // Returns: { | |||||
* > // a: 1, | |||||
* > // b: 2, | |||||
* > // c: '3', | |||||
* > // d: [ 5 ] | |||||
* > // }; | |||||
* | |||||
* @param {Object+} Any number of objects. | |||||
* @return {Object} The merged object. | |||||
*/ | |||||
function __extend() { | |||||
var i, | |||||
k, | |||||
res = {}, | |||||
l = arguments.length; | |||||
for (i = l - 1; i >= 0; i--) | |||||
for (k in arguments[i]) | |||||
res[k] = arguments[i][k]; | |||||
return res; | |||||
} | |||||
/** | |||||
* This function simply clones an object. This object must contain only | |||||
* objects, arrays and immutable values. Since it is not public, it does not | |||||
* deal with cyclic references, DOM elements and instantiated objects - so | |||||
* use it carefully. | |||||
* | |||||
* @param {Object} The object to clone. | |||||
* @return {Object} The clone. | |||||
*/ | |||||
function __clone(item) { | |||||
var result, i, k, l; | |||||
if (!item) | |||||
return item; | |||||
if (Array.isArray(item)) { | |||||
result = []; | |||||
for (i = 0, l = item.length; i < l; i++) | |||||
result.push(__clone(item[i])); | |||||
} else if (typeof item === 'object') { | |||||
result = {}; | |||||
for (i in item) | |||||
result[i] = __clone(item[i]); | |||||
} else | |||||
result = item; | |||||
return result; | |||||
} | |||||
/** | |||||
* Returns an array containing the values of an object. | |||||
* | |||||
* @param {Object} The object. | |||||
* @return {Array} The array of values. | |||||
*/ | |||||
function __objectValues(o) { | |||||
var k, | |||||
a = []; | |||||
for (k in o) | |||||
a.push(o[k]); | |||||
return a; | |||||
} | |||||
/** | |||||
* A short "Date.now()" polyfill. | |||||
* | |||||
* @return {Number} The current time (in ms). | |||||
*/ | |||||
function __dateNow() { | |||||
return Date.now ? Date.now() : new Date().getTime(); | |||||
} | |||||
/** | |||||
* Polyfill for the Array.isArray function: | |||||
*/ | |||||
if (!Array.isArray) | |||||
Array.isArray = function(v) { | |||||
return Object.prototype.toString.call(v) === '[object Array]'; | |||||
}; | |||||
/** | |||||
* EXPORT PUBLIC API: | |||||
* ****************** | |||||
*/ | |||||
var conrad = { | |||||
hasJob: _hasJob, | |||||
addJob: _addJob, | |||||
killJob: _killJob, | |||||
killAll: _killAll, | |||||
settings: _settings, | |||||
getStats: _getStats, | |||||
isRunning: _getIsRunning, | |||||
clearHistory: _clearHistory, | |||||
// Events management: | |||||
bind: _bind, | |||||
unbind: _unbind, | |||||
// Version: | |||||
version: '0.1.0' | |||||
}; | |||||
if (typeof exports !== 'undefined') { | |||||
if (typeof module !== 'undefined' && module.exports) | |||||
exports = module.exports = conrad; | |||||
exports.conrad = conrad; | |||||
} | |||||
global.conrad = conrad; | |||||
})(this); |
@ -0,0 +1,35 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.middlewares'); | |||||
/** | |||||
* This middleware will just copy the graphic properties. | |||||
* | |||||
* @param {?string} readPrefix The read prefix. | |||||
* @param {?string} writePrefix The write prefix. | |||||
*/ | |||||
sigma.middlewares.copy = function(readPrefix, writePrefix) { | |||||
var i, | |||||
l, | |||||
a; | |||||
if (writePrefix + '' === readPrefix + '') | |||||
return; | |||||
a = this.graph.nodes(); | |||||
for (i = 0, l = a.length; i < l; i++) { | |||||
a[i][writePrefix + 'x'] = a[i][readPrefix + 'x']; | |||||
a[i][writePrefix + 'y'] = a[i][readPrefix + 'y']; | |||||
a[i][writePrefix + 'size'] = a[i][readPrefix + 'size']; | |||||
} | |||||
a = this.graph.edges(); | |||||
for (i = 0, l = a.length; i < l; i++) | |||||
a[i][writePrefix + 'size'] = a[i][readPrefix + 'size']; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,189 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.middlewares'); | |||||
sigma.utils.pkg('sigma.utils'); | |||||
/** | |||||
* This middleware will rescale the graph such that it takes an optimal space | |||||
* on the renderer. | |||||
* | |||||
* As each middleware, this function is executed in the scope of the sigma | |||||
* instance. | |||||
* | |||||
* @param {?string} readPrefix The read prefix. | |||||
* @param {?string} writePrefix The write prefix. | |||||
* @param {object} options The parameters. | |||||
*/ | |||||
sigma.middlewares.rescale = function(readPrefix, writePrefix, options) { | |||||
var i, | |||||
l, | |||||
a, | |||||
b, | |||||
c, | |||||
d, | |||||
scale, | |||||
margin, | |||||
n = this.graph.nodes(), | |||||
e = this.graph.edges(), | |||||
settings = this.settings.embedObjects(options || {}), | |||||
bounds = settings('bounds') || sigma.utils.getBoundaries( | |||||
this.graph, | |||||
readPrefix, | |||||
true | |||||
), | |||||
minX = bounds.minX, | |||||
minY = bounds.minY, | |||||
maxX = bounds.maxX, | |||||
maxY = bounds.maxY, | |||||
sizeMax = bounds.sizeMax, | |||||
weightMax = bounds.weightMax, | |||||
w = settings('width') || 1, | |||||
h = settings('height') || 1, | |||||
rescaleSettings = settings('autoRescale'), | |||||
validSettings = { | |||||
nodePosition: 1, | |||||
nodeSize: 1, | |||||
edgeSize: 1 | |||||
}; | |||||
/** | |||||
* What elements should we rescale? | |||||
*/ | |||||
if (!(rescaleSettings instanceof Array)) | |||||
rescaleSettings = ['nodePosition', 'nodeSize', 'edgeSize']; | |||||
for (i = 0, l = rescaleSettings.length; i < l; i++) | |||||
if (!validSettings[rescaleSettings[i]]) | |||||
throw new Error( | |||||
'The rescale setting "' + rescaleSettings[i] + '" is not recognized.' | |||||
); | |||||
var np = ~rescaleSettings.indexOf('nodePosition'), | |||||
ns = ~rescaleSettings.indexOf('nodeSize'), | |||||
es = ~rescaleSettings.indexOf('edgeSize'); | |||||
/** | |||||
* First, we compute the scaling ratio, without considering the sizes | |||||
* of the nodes : Each node will have its center in the canvas, but might | |||||
* be partially out of it. | |||||
*/ | |||||
scale = settings('scalingMode') === 'outside' ? | |||||
Math.max( | |||||
w / Math.max(maxX - minX, 1), | |||||
h / Math.max(maxY - minY, 1) | |||||
) : | |||||
Math.min( | |||||
w / Math.max(maxX - minX, 1), | |||||
h / Math.max(maxY - minY, 1) | |||||
); | |||||
/** | |||||
* Then, we correct that scaling ratio considering a margin, which is | |||||
* basically the size of the biggest node. | |||||
* This has to be done as a correction since to compare the size of the | |||||
* biggest node to the X and Y values, we have to first get an | |||||
* approximation of the scaling ratio. | |||||
**/ | |||||
margin = | |||||
( | |||||
settings('rescaleIgnoreSize') ? | |||||
0 : | |||||
(settings('maxNodeSize') || sizeMax) / scale | |||||
) + | |||||
(settings('sideMargin') || 0); | |||||
maxX += margin; | |||||
minX -= margin; | |||||
maxY += margin; | |||||
minY -= margin; | |||||
// Fix the scaling with the new extrema: | |||||
scale = settings('scalingMode') === 'outside' ? | |||||
Math.max( | |||||
w / Math.max(maxX - minX, 1), | |||||
h / Math.max(maxY - minY, 1) | |||||
) : | |||||
Math.min( | |||||
w / Math.max(maxX - minX, 1), | |||||
h / Math.max(maxY - minY, 1) | |||||
); | |||||
// Size homothetic parameters: | |||||
if (!settings('maxNodeSize') && !settings('minNodeSize')) { | |||||
a = 1; | |||||
b = 0; | |||||
} else if (settings('maxNodeSize') === settings('minNodeSize')) { | |||||
a = 0; | |||||
b = +settings('maxNodeSize'); | |||||
} else { | |||||
a = (settings('maxNodeSize') - settings('minNodeSize')) / sizeMax; | |||||
b = +settings('minNodeSize'); | |||||
} | |||||
if (!settings('maxEdgeSize') && !settings('minEdgeSize')) { | |||||
c = 1; | |||||
d = 0; | |||||
} else if (settings('maxEdgeSize') === settings('minEdgeSize')) { | |||||
c = 0; | |||||
d = +settings('minEdgeSize'); | |||||
} else { | |||||
c = (settings('maxEdgeSize') - settings('minEdgeSize')) / weightMax; | |||||
d = +settings('minEdgeSize'); | |||||
} | |||||
// Rescale the nodes and edges: | |||||
for (i = 0, l = e.length; i < l; i++) | |||||
e[i][writePrefix + 'size'] = | |||||
e[i][readPrefix + 'size'] * (es ? c : 1) + (es ? d : 0); | |||||
for (i = 0, l = n.length; i < l; i++) { | |||||
n[i][writePrefix + 'size'] = | |||||
n[i][readPrefix + 'size'] * (ns ? a : 1) + (ns ? b : 0); | |||||
n[i][writePrefix + 'x'] = | |||||
(n[i][readPrefix + 'x'] - (maxX + minX) / 2) * (np ? scale : 1); | |||||
n[i][writePrefix + 'y'] = | |||||
(n[i][readPrefix + 'y'] - (maxY + minY) / 2) * (np ? scale : 1); | |||||
} | |||||
}; | |||||
sigma.utils.getBoundaries = function(graph, prefix, doEdges) { | |||||
var i, | |||||
l, | |||||
e = graph.edges(), | |||||
n = graph.nodes(), | |||||
weightMax = -Infinity, | |||||
sizeMax = -Infinity, | |||||
minX = Infinity, | |||||
minY = Infinity, | |||||
maxX = -Infinity, | |||||
maxY = -Infinity; | |||||
if (doEdges) | |||||
for (i = 0, l = e.length; i < l; i++) | |||||
weightMax = Math.max(e[i][prefix + 'size'], weightMax); | |||||
for (i = 0, l = n.length; i < l; i++) { | |||||
sizeMax = Math.max(n[i][prefix + 'size'], sizeMax); | |||||
maxX = Math.max(n[i][prefix + 'x'], maxX); | |||||
minX = Math.min(n[i][prefix + 'x'], minX); | |||||
maxY = Math.max(n[i][prefix + 'y'], maxY); | |||||
minY = Math.min(n[i][prefix + 'y'], minY); | |||||
} | |||||
weightMax = weightMax || 1; | |||||
sizeMax = sizeMax || 1; | |||||
return { | |||||
weightMax: weightMax, | |||||
sizeMax: sizeMax, | |||||
minX: minX, | |||||
minY: minY, | |||||
maxX: maxX, | |||||
maxY: maxY | |||||
}; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,239 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.misc.animation.running'); | |||||
/** | |||||
* Generates a unique ID for the animation. | |||||
* | |||||
* @return {string} Returns the new ID. | |||||
*/ | |||||
var _getID = (function() { | |||||
var id = 0; | |||||
return function() { | |||||
return '' + (++id); | |||||
}; | |||||
})(); | |||||
/** | |||||
* This function animates a camera. It has to be called with the camera to | |||||
* animate, the values of the coordinates to reach and eventually some | |||||
* options. It returns a number id, that you can use to kill the animation, | |||||
* with the method sigma.misc.animation.kill(id). | |||||
* | |||||
* The available options are: | |||||
* | |||||
* {?number} duration The duration of the animation. | |||||
* {?function} onNewFrame A callback to execute when the animation | |||||
* enter a new frame. | |||||
* {?function} onComplete A callback to execute when the animation | |||||
* is completed or killed. | |||||
* {?(string|function)} easing The name of a function from the package | |||||
* sigma.utils.easings, or a custom easing | |||||
* function. | |||||
* | |||||
* @param {camera} camera The camera to animate. | |||||
* @param {object} target The coordinates to reach. | |||||
* @param {?object} options Eventually an object to specify some options to | |||||
* the function. The available options are | |||||
* presented in the description of the function. | |||||
* @return {number} The animation id, to make it easy to kill | |||||
* through the method "sigma.misc.animation.kill". | |||||
*/ | |||||
sigma.misc.animation.camera = function(camera, val, options) { | |||||
if ( | |||||
!(camera instanceof sigma.classes.camera) || | |||||
typeof val !== 'object' || | |||||
!val | |||||
) | |||||
throw 'animation.camera: Wrong arguments.'; | |||||
if ( | |||||
typeof val.x !== 'number' && | |||||
typeof val.y !== 'number' && | |||||
typeof val.ratio !== 'number' && | |||||
typeof val.angle !== 'number' | |||||
) | |||||
throw 'There must be at least one valid coordinate in the given val.'; | |||||
var fn, | |||||
id, | |||||
anim, | |||||
easing, | |||||
duration, | |||||
initialVal, | |||||
o = options || {}, | |||||
start = sigma.utils.dateNow(); | |||||
// Store initial values: | |||||
initialVal = { | |||||
x: camera.x, | |||||
y: camera.y, | |||||
ratio: camera.ratio, | |||||
angle: camera.angle | |||||
}; | |||||
duration = o.duration; | |||||
easing = typeof o.easing !== 'function' ? | |||||
sigma.utils.easings[o.easing || 'quadraticInOut'] : | |||||
o.easing; | |||||
fn = function() { | |||||
var coef, | |||||
t = o.duration ? (sigma.utils.dateNow() - start) / o.duration : 1; | |||||
// If the animation is over: | |||||
if (t >= 1) { | |||||
camera.isAnimated = false; | |||||
camera.goTo({ | |||||
x: val.x !== undefined ? val.x : initialVal.x, | |||||
y: val.y !== undefined ? val.y : initialVal.y, | |||||
ratio: val.ratio !== undefined ? val.ratio : initialVal.ratio, | |||||
angle: val.angle !== undefined ? val.angle : initialVal.angle | |||||
}); | |||||
cancelAnimationFrame(id); | |||||
delete sigma.misc.animation.running[id]; | |||||
// Check callbacks: | |||||
if (typeof o.onComplete === 'function') | |||||
o.onComplete(); | |||||
// Else, let's keep going: | |||||
} else { | |||||
coef = easing(t); | |||||
camera.isAnimated = true; | |||||
camera.goTo({ | |||||
x: val.x !== undefined ? | |||||
initialVal.x + (val.x - initialVal.x) * coef : | |||||
initialVal.x, | |||||
y: val.y !== undefined ? | |||||
initialVal.y + (val.y - initialVal.y) * coef : | |||||
initialVal.y, | |||||
ratio: val.ratio !== undefined ? | |||||
initialVal.ratio + (val.ratio - initialVal.ratio) * coef : | |||||
initialVal.ratio, | |||||
angle: val.angle !== undefined ? | |||||
initialVal.angle + (val.angle - initialVal.angle) * coef : | |||||
initialVal.angle | |||||
}); | |||||
// Check callbacks: | |||||
if (typeof o.onNewFrame === 'function') | |||||
o.onNewFrame(); | |||||
anim.frameId = requestAnimationFrame(fn); | |||||
} | |||||
}; | |||||
id = _getID(); | |||||
anim = { | |||||
frameId: requestAnimationFrame(fn), | |||||
target: camera, | |||||
type: 'camera', | |||||
options: o, | |||||
fn: fn | |||||
}; | |||||
sigma.misc.animation.running[id] = anim; | |||||
return id; | |||||
}; | |||||
/** | |||||
* Kills a running animation. It triggers the eventual onComplete callback. | |||||
* | |||||
* @param {number} id The id of the animation to kill. | |||||
* @return {object} Returns the sigma.misc.animation package. | |||||
*/ | |||||
sigma.misc.animation.kill = function(id) { | |||||
if (arguments.length !== 1 || typeof id !== 'number') | |||||
throw 'animation.kill: Wrong arguments.'; | |||||
var o = sigma.misc.animation.running[id]; | |||||
if (o) { | |||||
cancelAnimationFrame(id); | |||||
delete sigma.misc.animation.running[o.frameId]; | |||||
if (o.type === 'camera') | |||||
o.target.isAnimated = false; | |||||
// Check callbacks: | |||||
if (typeof (o.options || {}).onComplete === 'function') | |||||
o.options.onComplete(); | |||||
} | |||||
return this; | |||||
}; | |||||
/** | |||||
* Kills every running animations, or only the one with the specified type, | |||||
* if a string parameter is given. | |||||
* | |||||
* @param {?(string|object)} filter A string to filter the animations to kill | |||||
* on their type (example: "camera"), or an | |||||
* object to filter on their target. | |||||
* @return {number} Returns the number of animations killed | |||||
* that way. | |||||
*/ | |||||
sigma.misc.animation.killAll = function(filter) { | |||||
var o, | |||||
id, | |||||
count = 0, | |||||
type = typeof filter === 'string' ? filter : null, | |||||
target = typeof filter === 'object' ? filter : null, | |||||
running = sigma.misc.animation.running; | |||||
for (id in running) | |||||
if ( | |||||
(!type || running[id].type === type) && | |||||
(!target || running[id].target === target) | |||||
) { | |||||
o = sigma.misc.animation.running[id]; | |||||
cancelAnimationFrame(o.frameId); | |||||
delete sigma.misc.animation.running[id]; | |||||
if (o.type === 'camera') | |||||
o.target.isAnimated = false; | |||||
// Increment counter: | |||||
count++; | |||||
// Check callbacks: | |||||
if (typeof (o.options || {}).onComplete === 'function') | |||||
o.options.onComplete(); | |||||
} | |||||
return count; | |||||
}; | |||||
/** | |||||
* Returns "true" if any animation that is currently still running matches | |||||
* the filter given to the function. | |||||
* | |||||
* @param {string|object} filter A string to filter the animations to kill | |||||
* on their type (example: "camera"), or an | |||||
* object to filter on their target. | |||||
* @return {boolean} Returns true if any running animation | |||||
* matches. | |||||
*/ | |||||
sigma.misc.animation.has = function(filter) { | |||||
var id, | |||||
type = typeof filter === 'string' ? filter : null, | |||||
target = typeof filter === 'object' ? filter : null, | |||||
running = sigma.misc.animation.running; | |||||
for (id in running) | |||||
if ( | |||||
(!type || running[id].type === type) && | |||||
(!target || running[id].target === target) | |||||
) | |||||
return true; | |||||
return false; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,156 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.misc'); | |||||
/** | |||||
* This helper will bind any DOM renderer (for instance svg) | |||||
* to its captors, to properly dispatch the good events to the sigma instance | |||||
* to manage clicking, hovering etc... | |||||
* | |||||
* It has to be called in the scope of the related renderer. | |||||
*/ | |||||
sigma.misc.bindDOMEvents = function(container) { | |||||
var self = this, | |||||
graph = this.graph; | |||||
// DOMElement abstraction | |||||
function Element(domElement) { | |||||
// Helpers | |||||
this.attr = function(attrName) { | |||||
return domElement.getAttributeNS(null, attrName); | |||||
}; | |||||
// Properties | |||||
this.tag = domElement.tagName; | |||||
this.class = this.attr('class'); | |||||
this.id = this.attr('id'); | |||||
// Methods | |||||
this.isNode = function() { | |||||
return !!~this.class.indexOf(self.settings('classPrefix') + '-node'); | |||||
}; | |||||
this.isEdge = function() { | |||||
return !!~this.class.indexOf(self.settings('classPrefix') + '-edge'); | |||||
}; | |||||
this.isHover = function() { | |||||
return !!~this.class.indexOf(self.settings('classPrefix') + '-hover'); | |||||
}; | |||||
} | |||||
// Click | |||||
function click(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
// Generic event | |||||
self.dispatchEvent('click', e); | |||||
// Are we on a node? | |||||
var element = new Element(e.target); | |||||
if (element.isNode()) | |||||
self.dispatchEvent('clickNode', { | |||||
node: graph.nodes(element.attr('data-node-id')) | |||||
}); | |||||
else | |||||
self.dispatchEvent('clickStage'); | |||||
e.preventDefault(); | |||||
e.stopPropagation(); | |||||
} | |||||
// Double click | |||||
function doubleClick(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
// Generic event | |||||
self.dispatchEvent('doubleClick', e); | |||||
// Are we on a node? | |||||
var element = new Element(e.target); | |||||
if (element.isNode()) | |||||
self.dispatchEvent('doubleClickNode', { | |||||
node: graph.nodes(element.attr('data-node-id')) | |||||
}); | |||||
else | |||||
self.dispatchEvent('doubleClickStage'); | |||||
e.preventDefault(); | |||||
e.stopPropagation(); | |||||
} | |||||
// On over | |||||
function onOver(e) { | |||||
var target = e.toElement || e.target; | |||||
if (!self.settings('eventsEnabled') || !target) | |||||
return; | |||||
var el = new Element(target); | |||||
if (el.isNode()) { | |||||
self.dispatchEvent('overNode', { | |||||
node: graph.nodes(el.attr('data-node-id')) | |||||
}); | |||||
} | |||||
else if (el.isEdge()) { | |||||
var edge = graph.edges(el.attr('data-edge-id')); | |||||
self.dispatchEvent('overEdge', { | |||||
edge: edge, | |||||
source: graph.nodes(edge.source), | |||||
target: graph.nodes(edge.target) | |||||
}); | |||||
} | |||||
} | |||||
// On out | |||||
function onOut(e) { | |||||
var target = e.fromElement || e.originalTarget; | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
var el = new Element(target); | |||||
if (el.isNode()) { | |||||
self.dispatchEvent('outNode', { | |||||
node: graph.nodes(el.attr('data-node-id')) | |||||
}); | |||||
} | |||||
else if (el.isEdge()) { | |||||
var edge = graph.edges(el.attr('data-edge-id')); | |||||
self.dispatchEvent('outEdge', { | |||||
edge: edge, | |||||
source: graph.nodes(edge.source), | |||||
target: graph.nodes(edge.target) | |||||
}); | |||||
} | |||||
} | |||||
// Registering Events: | |||||
// Click | |||||
container.addEventListener('click', click, false); | |||||
sigma.utils.doubleClick(container, 'click', doubleClick); | |||||
// Touch counterparts | |||||
container.addEventListener('touchstart', click, false); | |||||
sigma.utils.doubleClick(container, 'touchstart', doubleClick); | |||||
// Mouseover | |||||
container.addEventListener('mouseover', onOver, true); | |||||
// Mouseout | |||||
container.addEventListener('mouseout', onOut, true); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,509 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.misc'); | |||||
/** | |||||
* This helper will bind any no-DOM renderer (for instance canvas or WebGL) | |||||
* to its captors, to properly dispatch the good events to the sigma instance | |||||
* to manage clicking, hovering etc... | |||||
* | |||||
* It has to be called in the scope of the related renderer. | |||||
*/ | |||||
sigma.misc.bindEvents = function(prefix) { | |||||
var i, | |||||
l, | |||||
mX, | |||||
mY, | |||||
captor, | |||||
self = this; | |||||
function getNodes(e) { | |||||
if (e) { | |||||
mX = 'x' in e.data ? e.data.x : mX; | |||||
mY = 'y' in e.data ? e.data.y : mY; | |||||
} | |||||
var i, | |||||
j, | |||||
l, | |||||
n, | |||||
x, | |||||
y, | |||||
s, | |||||
inserted, | |||||
selected = [], | |||||
modifiedX = mX + self.width / 2, | |||||
modifiedY = mY + self.height / 2, | |||||
point = self.camera.cameraPosition( | |||||
mX, | |||||
mY | |||||
), | |||||
nodes = self.camera.quadtree.point( | |||||
point.x, | |||||
point.y | |||||
); | |||||
if (nodes.length) | |||||
for (i = 0, l = nodes.length; i < l; i++) { | |||||
n = nodes[i]; | |||||
x = n[prefix + 'x']; | |||||
y = n[prefix + 'y']; | |||||
s = n[prefix + 'size']; | |||||
if ( | |||||
!n.hidden && | |||||
modifiedX > x - s && | |||||
modifiedX < x + s && | |||||
modifiedY > y - s && | |||||
modifiedY < y + s && | |||||
Math.sqrt( | |||||
Math.pow(modifiedX - x, 2) + | |||||
Math.pow(modifiedY - y, 2) | |||||
) < s | |||||
) { | |||||
// Insert the node: | |||||
inserted = false; | |||||
for (j = 0; j < selected.length; j++) | |||||
if (n.size > selected[j].size) { | |||||
selected.splice(j, 0, n); | |||||
inserted = true; | |||||
break; | |||||
} | |||||
if (!inserted) | |||||
selected.push(n); | |||||
} | |||||
} | |||||
return selected; | |||||
} | |||||
function getEdges(e) { | |||||
if (!self.settings('enableEdgeHovering')) { | |||||
// No event if the setting is off: | |||||
return []; | |||||
} | |||||
var isCanvas = ( | |||||
sigma.renderers.canvas && self instanceof sigma.renderers.canvas); | |||||
if (!isCanvas) { | |||||
// A quick hardcoded rule to prevent people from using this feature | |||||
// with the WebGL renderer (which is not good enough at the moment): | |||||
throw new Error( | |||||
'The edge events feature is not compatible with the WebGL renderer' | |||||
); | |||||
} | |||||
if (e) { | |||||
mX = 'x' in e.data ? e.data.x : mX; | |||||
mY = 'y' in e.data ? e.data.y : mY; | |||||
} | |||||
var i, | |||||
j, | |||||
l, | |||||
a, | |||||
edge, | |||||
s, | |||||
maxEpsilon = self.settings('edgeHoverPrecision'), | |||||
source, | |||||
target, | |||||
cp, | |||||
nodeIndex = {}, | |||||
inserted, | |||||
selected = [], | |||||
modifiedX = mX + self.width / 2, | |||||
modifiedY = mY + self.height / 2, | |||||
point = self.camera.cameraPosition( | |||||
mX, | |||||
mY | |||||
), | |||||
edges = []; | |||||
if (isCanvas) { | |||||
var nodesOnScreen = self.camera.quadtree.area( | |||||
self.camera.getRectangle(self.width, self.height) | |||||
); | |||||
for (a = nodesOnScreen, i = 0, l = a.length; i < l; i++) | |||||
nodeIndex[a[i].id] = a[i]; | |||||
} | |||||
if (self.camera.edgequadtree !== undefined) { | |||||
edges = self.camera.edgequadtree.point( | |||||
point.x, | |||||
point.y | |||||
); | |||||
} | |||||
function insertEdge(selected, edge) { | |||||
inserted = false; | |||||
for (j = 0; j < selected.length; j++) | |||||
if (edge.size > selected[j].size) { | |||||
selected.splice(j, 0, edge); | |||||
inserted = true; | |||||
break; | |||||
} | |||||
if (!inserted) | |||||
selected.push(edge); | |||||
} | |||||
if (edges.length) | |||||
for (i = 0, l = edges.length; i < l; i++) { | |||||
edge = edges[i]; | |||||
source = self.graph.nodes(edge.source); | |||||
target = self.graph.nodes(edge.target); | |||||
// (HACK) we can't get edge[prefix + 'size'] on WebGL renderer: | |||||
s = edge[prefix + 'size'] || | |||||
edge['read_' + prefix + 'size']; | |||||
// First, let's identify which edges are drawn. To do this, we keep | |||||
// every edges that have at least one extremity displayed according to | |||||
// the quadtree and the "hidden" attribute. We also do not keep hidden | |||||
// edges. | |||||
// Then, let's check if the mouse is on the edge (we suppose that it | |||||
// is a line segment). | |||||
if ( | |||||
!edge.hidden && | |||||
!source.hidden && !target.hidden && | |||||
(!isCanvas || | |||||
(nodeIndex[edge.source] || nodeIndex[edge.target])) && | |||||
sigma.utils.getDistance( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'], | |||||
modifiedX, | |||||
modifiedY) > source[prefix + 'size'] && | |||||
sigma.utils.getDistance( | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'], | |||||
modifiedX, | |||||
modifiedY) > target[prefix + 'size'] | |||||
) { | |||||
if (edge.type == 'curve' || edge.type == 'curvedArrow') { | |||||
if (source.id === target.id) { | |||||
cp = sigma.utils.getSelfLoopControlPoints( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'], | |||||
source[prefix + 'size'] | |||||
); | |||||
if ( | |||||
sigma.utils.isPointOnBezierCurve( | |||||
modifiedX, | |||||
modifiedY, | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'], | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'], | |||||
cp.x1, | |||||
cp.y1, | |||||
cp.x2, | |||||
cp.y2, | |||||
Math.max(s, maxEpsilon) | |||||
)) { | |||||
insertEdge(selected, edge); | |||||
} | |||||
} | |||||
else { | |||||
cp = sigma.utils.getQuadraticControlPoint( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'], | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y']); | |||||
if ( | |||||
sigma.utils.isPointOnQuadraticCurve( | |||||
modifiedX, | |||||
modifiedY, | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'], | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'], | |||||
cp.x, | |||||
cp.y, | |||||
Math.max(s, maxEpsilon) | |||||
)) { | |||||
insertEdge(selected, edge); | |||||
} | |||||
} | |||||
} else if ( | |||||
sigma.utils.isPointOnSegment( | |||||
modifiedX, | |||||
modifiedY, | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'], | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'], | |||||
Math.max(s, maxEpsilon) | |||||
)) { | |||||
insertEdge(selected, edge); | |||||
} | |||||
} | |||||
} | |||||
return selected; | |||||
} | |||||
function bindCaptor(captor) { | |||||
var nodes, | |||||
edges, | |||||
overNodes = {}, | |||||
overEdges = {}; | |||||
function onClick(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
self.dispatchEvent('click', e.data); | |||||
nodes = getNodes(e); | |||||
edges = getEdges(e); | |||||
if (nodes.length) { | |||||
self.dispatchEvent('clickNode', { | |||||
node: nodes[0], | |||||
captor: e.data | |||||
}); | |||||
self.dispatchEvent('clickNodes', { | |||||
node: nodes, | |||||
captor: e.data | |||||
}); | |||||
} else if (edges.length) { | |||||
self.dispatchEvent('clickEdge', { | |||||
edge: edges[0], | |||||
captor: e.data | |||||
}); | |||||
self.dispatchEvent('clickEdges', { | |||||
edge: edges, | |||||
captor: e.data | |||||
}); | |||||
} else | |||||
self.dispatchEvent('clickStage', {captor: e.data}); | |||||
} | |||||
function onDoubleClick(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
self.dispatchEvent('doubleClick', e.data); | |||||
nodes = getNodes(e); | |||||
edges = getEdges(e); | |||||
if (nodes.length) { | |||||
self.dispatchEvent('doubleClickNode', { | |||||
node: nodes[0], | |||||
captor: e.data | |||||
}); | |||||
self.dispatchEvent('doubleClickNodes', { | |||||
node: nodes, | |||||
captor: e.data | |||||
}); | |||||
} else if (edges.length) { | |||||
self.dispatchEvent('doubleClickEdge', { | |||||
edge: edges[0], | |||||
captor: e.data | |||||
}); | |||||
self.dispatchEvent('doubleClickEdges', { | |||||
edge: edges, | |||||
captor: e.data | |||||
}); | |||||
} else | |||||
self.dispatchEvent('doubleClickStage', {captor: e.data}); | |||||
} | |||||
function onRightClick(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
self.dispatchEvent('rightClick', e.data); | |||||
nodes = getNodes(e); | |||||
edges = getEdges(e); | |||||
if (nodes.length) { | |||||
self.dispatchEvent('rightClickNode', { | |||||
node: nodes[0], | |||||
captor: e.data | |||||
}); | |||||
self.dispatchEvent('rightClickNodes', { | |||||
node: nodes, | |||||
captor: e.data | |||||
}); | |||||
} else if (edges.length) { | |||||
self.dispatchEvent('rightClickEdge', { | |||||
edge: edges[0], | |||||
captor: e.data | |||||
}); | |||||
self.dispatchEvent('rightClickEdges', { | |||||
edge: edges, | |||||
captor: e.data | |||||
}); | |||||
} else | |||||
self.dispatchEvent('rightClickStage', {captor: e.data}); | |||||
} | |||||
function onOut(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
var k, | |||||
i, | |||||
l, | |||||
le, | |||||
outNodes = [], | |||||
outEdges = []; | |||||
for (k in overNodes) | |||||
outNodes.push(overNodes[k]); | |||||
overNodes = {}; | |||||
// Dispatch both single and multi events: | |||||
for (i = 0, l = outNodes.length; i < l; i++) | |||||
self.dispatchEvent('outNode', { | |||||
node: outNodes[i], | |||||
captor: e.data | |||||
}); | |||||
if (outNodes.length) | |||||
self.dispatchEvent('outNodes', { | |||||
nodes: outNodes, | |||||
captor: e.data | |||||
}); | |||||
overEdges = {}; | |||||
// Dispatch both single and multi events: | |||||
for (i = 0, le = outEdges.length; i < le; i++) | |||||
self.dispatchEvent('outEdge', { | |||||
edge: outEdges[i], | |||||
captor: e.data | |||||
}); | |||||
if (outEdges.length) | |||||
self.dispatchEvent('outEdges', { | |||||
edges: outEdges, | |||||
captor: e.data | |||||
}); | |||||
} | |||||
function onMove(e) { | |||||
if (!self.settings('eventsEnabled')) | |||||
return; | |||||
nodes = getNodes(e); | |||||
edges = getEdges(e); | |||||
var i, | |||||
k, | |||||
node, | |||||
edge, | |||||
newOutNodes = [], | |||||
newOverNodes = [], | |||||
currentOverNodes = {}, | |||||
l = nodes.length, | |||||
newOutEdges = [], | |||||
newOverEdges = [], | |||||
currentOverEdges = {}, | |||||
le = edges.length; | |||||
// Check newly overred nodes: | |||||
for (i = 0; i < l; i++) { | |||||
node = nodes[i]; | |||||
currentOverNodes[node.id] = node; | |||||
if (!overNodes[node.id]) { | |||||
newOverNodes.push(node); | |||||
overNodes[node.id] = node; | |||||
} | |||||
} | |||||
// Check no more overred nodes: | |||||
for (k in overNodes) | |||||
if (!currentOverNodes[k]) { | |||||
newOutNodes.push(overNodes[k]); | |||||
delete overNodes[k]; | |||||
} | |||||
// Dispatch both single and multi events: | |||||
for (i = 0, l = newOverNodes.length; i < l; i++) | |||||
self.dispatchEvent('overNode', { | |||||
node: newOverNodes[i], | |||||
captor: e.data | |||||
}); | |||||
for (i = 0, l = newOutNodes.length; i < l; i++) | |||||
self.dispatchEvent('outNode', { | |||||
node: newOutNodes[i], | |||||
captor: e.data | |||||
}); | |||||
if (newOverNodes.length) | |||||
self.dispatchEvent('overNodes', { | |||||
nodes: newOverNodes, | |||||
captor: e.data | |||||
}); | |||||
if (newOutNodes.length) | |||||
self.dispatchEvent('outNodes', { | |||||
nodes: newOutNodes, | |||||
captor: e.data | |||||
}); | |||||
// Check newly overred edges: | |||||
for (i = 0; i < le; i++) { | |||||
edge = edges[i]; | |||||
currentOverEdges[edge.id] = edge; | |||||
if (!overEdges[edge.id]) { | |||||
newOverEdges.push(edge); | |||||
overEdges[edge.id] = edge; | |||||
} | |||||
} | |||||
// Check no more overred edges: | |||||
for (k in overEdges) | |||||
if (!currentOverEdges[k]) { | |||||
newOutEdges.push(overEdges[k]); | |||||
delete overEdges[k]; | |||||
} | |||||
// Dispatch both single and multi events: | |||||
for (i = 0, le = newOverEdges.length; i < le; i++) | |||||
self.dispatchEvent('overEdge', { | |||||
edge: newOverEdges[i], | |||||
captor: e.data | |||||
}); | |||||
for (i = 0, le = newOutEdges.length; i < le; i++) | |||||
self.dispatchEvent('outEdge', { | |||||
edge: newOutEdges[i], | |||||
captor: e.data | |||||
}); | |||||
if (newOverEdges.length) | |||||
self.dispatchEvent('overEdges', { | |||||
edges: newOverEdges, | |||||
captor: e.data | |||||
}); | |||||
if (newOutEdges.length) | |||||
self.dispatchEvent('outEdges', { | |||||
edges: newOutEdges, | |||||
captor: e.data | |||||
}); | |||||
} | |||||
// Bind events: | |||||
captor.bind('click', onClick); | |||||
captor.bind('mousedown', onMove); | |||||
captor.bind('mouseup', onMove); | |||||
captor.bind('mousemove', onMove); | |||||
captor.bind('mouseout', onOut); | |||||
captor.bind('doubleclick', onDoubleClick); | |||||
captor.bind('rightclick', onRightClick); | |||||
self.bind('render', onMove); | |||||
} | |||||
for (i = 0, l = this.captors.length; i < l; i++) | |||||
bindCaptor(this.captors[i]); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,222 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.misc'); | |||||
/** | |||||
* This method listens to "overNode", "outNode", "overEdge" and "outEdge" | |||||
* events from a renderer and renders the nodes differently on the top layer. | |||||
* The goal is to make any node label readable with the mouse, and to | |||||
* highlight hovered nodes and edges. | |||||
* | |||||
* It has to be called in the scope of the related renderer. | |||||
*/ | |||||
sigma.misc.drawHovers = function(prefix) { | |||||
var self = this, | |||||
hoveredNodes = {}, | |||||
hoveredEdges = {}; | |||||
this.bind('overNode', function(event) { | |||||
var node = event.data.node; | |||||
if (!node.hidden) { | |||||
hoveredNodes[node.id] = node; | |||||
draw(); | |||||
} | |||||
}); | |||||
this.bind('outNode', function(event) { | |||||
delete hoveredNodes[event.data.node.id]; | |||||
draw(); | |||||
}); | |||||
this.bind('overEdge', function(event) { | |||||
var edge = event.data.edge; | |||||
if (!edge.hidden) { | |||||
hoveredEdges[edge.id] = edge; | |||||
draw(); | |||||
} | |||||
}); | |||||
this.bind('outEdge', function(event) { | |||||
delete hoveredEdges[event.data.edge.id]; | |||||
draw(); | |||||
}); | |||||
this.bind('render', function(event) { | |||||
draw(); | |||||
}); | |||||
function draw() { | |||||
var k, | |||||
source, | |||||
target, | |||||
hoveredNode, | |||||
hoveredEdge, | |||||
c = self.contexts.hover.canvas, | |||||
defaultNodeType = self.settings('defaultNodeType'), | |||||
defaultEdgeType = self.settings('defaultEdgeType'), | |||||
nodeRenderers = sigma.canvas.hovers, | |||||
edgeRenderers = sigma.canvas.edgehovers, | |||||
extremitiesRenderers = sigma.canvas.extremities, | |||||
embedSettings = self.settings.embedObjects({ | |||||
prefix: prefix | |||||
}); | |||||
// Clear self.contexts.hover: | |||||
self.contexts.hover.clearRect(0, 0, c.width, c.height); | |||||
// Node render: single hover | |||||
if ( | |||||
embedSettings('enableHovering') && | |||||
embedSettings('singleHover') && | |||||
Object.keys(hoveredNodes).length | |||||
) { | |||||
hoveredNode = hoveredNodes[Object.keys(hoveredNodes)[0]]; | |||||
( | |||||
nodeRenderers[hoveredNode.type] || | |||||
nodeRenderers[defaultNodeType] || | |||||
nodeRenderers.def | |||||
)( | |||||
hoveredNode, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
} | |||||
// Node render: multiple hover | |||||
if ( | |||||
embedSettings('enableHovering') && | |||||
!embedSettings('singleHover') | |||||
) | |||||
for (k in hoveredNodes) | |||||
( | |||||
nodeRenderers[hoveredNodes[k].type] || | |||||
nodeRenderers[defaultNodeType] || | |||||
nodeRenderers.def | |||||
)( | |||||
hoveredNodes[k], | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
// Edge render: single hover | |||||
if ( | |||||
embedSettings('enableEdgeHovering') && | |||||
embedSettings('singleHover') && | |||||
Object.keys(hoveredEdges).length | |||||
) { | |||||
hoveredEdge = hoveredEdges[Object.keys(hoveredEdges)[0]]; | |||||
source = self.graph.nodes(hoveredEdge.source); | |||||
target = self.graph.nodes(hoveredEdge.target); | |||||
if (! hoveredEdge.hidden) { | |||||
( | |||||
edgeRenderers[hoveredEdge.type] || | |||||
edgeRenderers[defaultEdgeType] || | |||||
edgeRenderers.def | |||||
) ( | |||||
hoveredEdge, | |||||
source, | |||||
target, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
if (embedSettings('edgeHoverExtremities')) { | |||||
( | |||||
extremitiesRenderers[hoveredEdge.type] || | |||||
extremitiesRenderers.def | |||||
)( | |||||
hoveredEdge, | |||||
source, | |||||
target, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
} else { | |||||
// Avoid edges rendered over nodes: | |||||
( | |||||
sigma.canvas.nodes[source.type] || | |||||
sigma.canvas.nodes.def | |||||
) ( | |||||
source, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
( | |||||
sigma.canvas.nodes[target.type] || | |||||
sigma.canvas.nodes.def | |||||
) ( | |||||
target, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
} | |||||
} | |||||
} | |||||
// Edge render: multiple hover | |||||
if ( | |||||
embedSettings('enableEdgeHovering') && | |||||
!embedSettings('singleHover') | |||||
) { | |||||
for (k in hoveredEdges) { | |||||
hoveredEdge = hoveredEdges[k]; | |||||
source = self.graph.nodes(hoveredEdge.source); | |||||
target = self.graph.nodes(hoveredEdge.target); | |||||
if (!hoveredEdge.hidden) { | |||||
( | |||||
edgeRenderers[hoveredEdge.type] || | |||||
edgeRenderers[defaultEdgeType] || | |||||
edgeRenderers.def | |||||
) ( | |||||
hoveredEdge, | |||||
source, | |||||
target, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
if (embedSettings('edgeHoverExtremities')) { | |||||
( | |||||
extremitiesRenderers[hoveredEdge.type] || | |||||
extremitiesRenderers.def | |||||
)( | |||||
hoveredEdge, | |||||
source, | |||||
target, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
} else { | |||||
// Avoid edges rendered over nodes: | |||||
( | |||||
sigma.canvas.nodes[source.type] || | |||||
sigma.canvas.nodes.def | |||||
) ( | |||||
source, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
( | |||||
sigma.canvas.nodes[target.type] || | |||||
sigma.canvas.nodes.def | |||||
) ( | |||||
target, | |||||
self.contexts.hover, | |||||
embedSettings | |||||
); | |||||
} | |||||
} | |||||
} | |||||
} | |||||
} | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,41 @@ | |||||
sigma.exporters.svg | |||||
======================== | |||||
Plugin by [Guillaume Plique](https://github.com/Yomguithereal). | |||||
--- | |||||
This plugin aims at providing an easy way to export a graph as a SVG file. | |||||
*Basic usage* | |||||
```js | |||||
// Retrieving the svg file as a string | |||||
var svgString = sigInst.toSVG(); | |||||
// Dowload the svg file | |||||
sigInst.toSVG({download: true, filename: 'my-fancy-graph.svg'}); | |||||
``` | |||||
*Complex usage* | |||||
```js | |||||
sigInst.toSVG({ | |||||
labels: true, | |||||
classes: false, | |||||
data: true, | |||||
download: true, | |||||
filename: 'hello.svg' | |||||
}); | |||||
``` | |||||
*Parameters* | |||||
* **size** *?integer* [`1000`]: size of the svg canvas in pixels. | |||||
* **height** *?integer* [`1000`]: height of the svg canvas in pixels (useful only if you want a height different from the width). | |||||
* **width** *?integer* [`1000`]: width of the svg canvas in pixels (useful only if you want a width different from the height). | |||||
* **classes** *?boolean* [`true`]: should the exporter try to optimize the svg document by creating classes? | |||||
* **labels** *?boolean* [`false`]: should the labels be included in the svg file? | |||||
* **data** *?boolean* [`false`]: should additional data (node ids for instance) be included in the svg file? | |||||
* **download** *?boolean* [`false`]: should the exporter make the browser download the svg file? | |||||
* **filename** *?string* [`'graph.svg'`]: filename of the file to download. |
@ -0,0 +1,225 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
/** | |||||
* Sigma SVG Exporter | |||||
* =================== | |||||
* | |||||
* This plugin is designed to export a graph to a svg file that can be | |||||
* downloaded or just used elsewhere. | |||||
* | |||||
* Author: Guillaume Plique (Yomguithereal) | |||||
* Version: 0.0.1 | |||||
*/ | |||||
// Terminating if sigma were not to be found | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma.renderers.snapshot: sigma not in scope.'; | |||||
/** | |||||
* Polyfills | |||||
*/ | |||||
var URL = this.URL || this.webkitURL || this; | |||||
/** | |||||
* Utilities | |||||
*/ | |||||
function createBlob(data) { | |||||
return new Blob( | |||||
[data], | |||||
{type: 'image/svg+xml;charset=utf-8'} | |||||
); | |||||
} | |||||
function download(string, filename) { | |||||
// Creating blob href | |||||
var blob = createBlob(string); | |||||
// Anchor | |||||
var o = {}; | |||||
o.anchor = document.createElement('a'); | |||||
o.anchor.setAttribute('href', URL.createObjectURL(blob)); | |||||
o.anchor.setAttribute('download', filename); | |||||
// Click event | |||||
var event = document.createEvent('MouseEvent'); | |||||
event.initMouseEvent('click', true, false, window, 0, 0, 0 ,0, 0, | |||||
false, false, false, false, 0, null); | |||||
URL.revokeObjectURL(blob); | |||||
o.anchor.dispatchEvent(event); | |||||
delete o.anchor; | |||||
} | |||||
/** | |||||
* Defaults | |||||
*/ | |||||
var DEFAULTS = { | |||||
size: '1000', | |||||
width: '1000', | |||||
height: '1000', | |||||
classes: true, | |||||
labels: true, | |||||
data: false, | |||||
download: false, | |||||
filename: 'graph.svg' | |||||
}; | |||||
var XMLNS = 'http://www.w3.org/2000/svg'; | |||||
/** | |||||
* Subprocesses | |||||
*/ | |||||
function optimize(svg, prefix, params) { | |||||
var nodeColorIndex = {}, | |||||
edgeColorIndex = {}, | |||||
count = 0, | |||||
color, | |||||
style, | |||||
styleText = '', | |||||
f, | |||||
i, | |||||
l; | |||||
// Creating style tag if needed | |||||
if (params.classes) { | |||||
style = document.createElementNS(XMLNS, 'style'); | |||||
style.setAttribute('type', 'text/css') | |||||
svg.insertBefore(style, svg.firstChild); | |||||
} | |||||
// Iterating over nodes | |||||
var nodes = svg.querySelectorAll('[id="' + prefix + '-group-nodes"] > [class="' + prefix + '-node"]'); | |||||
for (i = 0, l = nodes.length, f = true; i < l; i++) { | |||||
color = nodes[i].getAttribute('fill'); | |||||
if (!params.data) | |||||
nodes[i].removeAttribute('data-node-id'); | |||||
if (params.classes) { | |||||
if (!(color in nodeColorIndex)) { | |||||
nodeColorIndex[color] = (f ? prefix + '-node' : 'c-' + (count++)); | |||||
styleText += '.' + nodeColorIndex[color] + '{fill: ' + color + '}'; | |||||
} | |||||
if (nodeColorIndex[color] !== prefix + '-node') | |||||
nodes[i].setAttribute('class', nodes[i].getAttribute('class') + ' ' + nodeColorIndex[color]); | |||||
nodes[i].removeAttribute('fill'); | |||||
} | |||||
f = false; | |||||
} | |||||
// Iterating over edges | |||||
var edges = svg.querySelectorAll('[id="' + prefix + '-group-edges"] > [class="' + prefix + '-edge"]'); | |||||
for (i = 0, l = edges.length, f = true; i < l; i++) { | |||||
color = edges[i].getAttribute('stroke'); | |||||
if (!params.data) | |||||
edges[i].removeAttribute('data-edge-id'); | |||||
if (params.classes) { | |||||
if (!(color in edgeColorIndex)) { | |||||
edgeColorIndex[color] = (f ? prefix + '-edge' : 'c-' + (count++)); | |||||
styleText += '.' + edgeColorIndex[color] + '{stroke: ' + color + '}'; | |||||
} | |||||
if (edgeColorIndex[color] !== prefix + '-edge') | |||||
edges[i].setAttribute('class', edges[i].getAttribute('class') + ' ' + edgeColorIndex[color]); | |||||
edges[i].removeAttribute('stroke'); | |||||
} | |||||
f = false; | |||||
} | |||||
if (params.classes) | |||||
style.appendChild(document.createTextNode(styleText)); | |||||
} | |||||
/** | |||||
* Extending prototype | |||||
*/ | |||||
sigma.prototype.toSVG = function(params) { | |||||
params = params || {}; | |||||
var prefix = this.settings('classPrefix'), | |||||
w = params.size || params.width || DEFAULTS.size, | |||||
h = params.size || params.height || DEFAULTS.size; | |||||
// Creating a dummy container | |||||
var container = document.createElement('div'); | |||||
container.setAttribute('width', w); | |||||
container.setAttribute('height', h); | |||||
container.setAttribute('style', 'position:absolute; top: 0px; left:0px; width: ' + w + 'px; height: ' + h + 'px;'); | |||||
// Creating a camera | |||||
var camera = this.addCamera(); | |||||
// Creating a svg renderer | |||||
var renderer = this.addRenderer({ | |||||
camera: camera, | |||||
container: container, | |||||
type: 'svg', | |||||
forceLabels: !!params.labels | |||||
}); | |||||
// Refreshing | |||||
renderer.resize(w, h); | |||||
this.refresh(); | |||||
// Dropping camera and renderers before something nasty happens | |||||
this.killRenderer(renderer); | |||||
this.killCamera(camera); | |||||
// Retrieving svg | |||||
var svg = container.querySelector('svg'); | |||||
svg.removeAttribute('style'); | |||||
svg.setAttribute('width', w + 'px'); | |||||
svg.setAttribute('height', h + 'px'); | |||||
svg.setAttribute('x', '0px'); | |||||
svg.setAttribute('y', '0px'); | |||||
// svg.setAttribute('viewBox', '0 0 1000 1000'); | |||||
// Dropping labels | |||||
if (!params.labels) { | |||||
var labelGroup = svg.querySelector('[id="' + prefix + '-group-labels"]'); | |||||
svg.removeChild(labelGroup); | |||||
} | |||||
// Dropping hovers | |||||
var hoverGroup = svg.querySelector('[id="' + prefix + '-group-hovers"]'); | |||||
svg.removeChild(hoverGroup); | |||||
// Optims? | |||||
params.classes = (params.classes !== false); | |||||
if (!params.data || params.classes) | |||||
optimize(svg, prefix, params); | |||||
// Retrieving svg string | |||||
var svgString = svg.outerHTML; | |||||
// Paranoid cleanup | |||||
container = null; | |||||
// Output string | |||||
var output = '<?xml version="1.0" encoding="utf-8"?>\n'; | |||||
output += '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'; | |||||
output += svgString; | |||||
if (params.download) | |||||
download(output, params.filename || DEFAULTS.filename); | |||||
return output; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,28 @@ | |||||
module.exports = function(grunt) { | |||||
// Setting grunt base as sigma's root directory | |||||
grunt.file.setBase('../../'); | |||||
// Registering needed files | |||||
var files = ['supervisor.js', 'worker.js'].map(function(p) { | |||||
return __dirname + '/' + p; | |||||
}); | |||||
// Project configuration: | |||||
grunt.initConfig({ | |||||
forceAtlas2: { | |||||
prod: { | |||||
files: { | |||||
'build/plugins/sigma.layout.forceAtlas2.min.js': files | |||||
} | |||||
} | |||||
} | |||||
}); | |||||
// Loading tasks | |||||
grunt.loadTasks(__dirname + '/tasks'); | |||||
// By default, we will crush and then minify | |||||
grunt.registerTask('default', ['forceAtlas2:prod']); | |||||
}; |
@ -0,0 +1,79 @@ | |||||
sigma.layout.forceAtlas2 | |||||
======================== | |||||
Algorithm by [Mathieu Jacomy](https://github.com/jacomyma). | |||||
Plugin by [Guillaume Plique](https://github.com/Yomguithereal). | |||||
--- | |||||
This plugin implements [ForceAtlas2](http://www.plosone.org/article/info%3Adoi%2F10.1371%2Fjournal.pone.0098679), a force-directed layout algorithm. | |||||
For optimization purposes, the algorithm's computations are delegated to a web worker. | |||||
## Methods | |||||
**sigma.startForceAtlas2** | |||||
Starts or unpauses the layout. It is possible to pass a configuration if this is the first time you start the layout. | |||||
```js | |||||
sigmaInstance.startForceAtlas2(config); | |||||
``` | |||||
**sigma.stopForceAtlas2** | |||||
Pauses the layout. | |||||
```js | |||||
sigmaInstance.stopForceAtlas2(); | |||||
``` | |||||
**sigma.configForceAtlas2** | |||||
Changes the layout's configuration. | |||||
```js | |||||
sigmaInstance.configForceAtlas2(config); | |||||
``` | |||||
**sigma.killForceAtlas2** | |||||
Completely stops the layout and terminates the assiociated worker. You can still restart it later, but a new worker will have to initialize. | |||||
```js | |||||
sigmaInstance.killForceAtlas2(); | |||||
``` | |||||
**sigma.isForceAtlas2Running** | |||||
Returns whether ForceAtlas2 is running. | |||||
```js | |||||
sigmaInstance.isForceAtlas2Running(); | |||||
``` | |||||
## Configuration | |||||
*Algorithm configuration* | |||||
* **linLogMode** *boolean* `false`: switch ForceAtlas' model from lin-lin to lin-log (tribute to Andreas Noack). Makes clusters more tight. | |||||
* **outboundAttractionDistribution** *boolean* `false` | |||||
* **adjustSizes** *boolean* `false` | |||||
* **edgeWeightInfluence** *number* `0`: how much influence you give to the edges weight. 0 is "no influence" and 1 is "normal". | |||||
* **scalingRatio** *number* `1`: how much repulsion you want. More makes a more sparse graph. | |||||
* **strongGravityMode** *boolean* `false` | |||||
* **gravity** *number* `1`: attracts nodes to the center. Prevents islands from drifting away. | |||||
* **barnesHutOptimize** *boolean* `true`: should we use the algorithm's Barnes-Hut to improve repulsion's scalability (`O(n²)` to `O(nlog(n))`)? This is useful for large graph but harmful to small ones. | |||||
* **barnesHutTheta** *number* `0.5` | |||||
* **slowDown** *number* `1` | |||||
* **startingIterations** *integer* `1`: number of iterations to be run before the first render. | |||||
* **iterationsPerRender** *integer* `1`: number of iterations to be run before each render. | |||||
*Supervisor configuration* | |||||
* **worker** *boolean* `true`: should the layout use a web worker? | |||||
* **workerUrl** *string* : path to the worker file if needed because your browser does not support blob workers. | |||||
## Notes | |||||
1. The layout won't stop by itself, so if you want it to stop, you will have to trigger it explicitly. |
@ -0,0 +1,340 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
/** | |||||
* Sigma ForceAtlas2.5 Supervisor | |||||
* =============================== | |||||
* | |||||
* Author: Guillaume Plique (Yomguithereal) | |||||
* Version: 0.1 | |||||
*/ | |||||
var _root = this; | |||||
/** | |||||
* Feature detection | |||||
* ------------------ | |||||
*/ | |||||
var webWorkers = 'Worker' in _root; | |||||
/** | |||||
* Supervisor Object | |||||
* ------------------ | |||||
*/ | |||||
function Supervisor(sigInst, options) { | |||||
var _this = this, | |||||
workerFn = sigInst.getForceAtlas2Worker && | |||||
sigInst.getForceAtlas2Worker(); | |||||
options = options || {}; | |||||
// _root URL Polyfill | |||||
_root.URL = _root.URL || _root.webkitURL; | |||||
// Properties | |||||
this.sigInst = sigInst; | |||||
this.graph = this.sigInst.graph; | |||||
this.ppn = 10; | |||||
this.ppe = 3; | |||||
this.config = {}; | |||||
this.shouldUseWorker = | |||||
options.worker === false ? false : true && webWorkers; | |||||
this.workerUrl = options.workerUrl; | |||||
// State | |||||
this.started = false; | |||||
this.running = false; | |||||
// Web worker or classic DOM events? | |||||
if (this.shouldUseWorker) { | |||||
if (!this.workerUrl) { | |||||
var blob = this.makeBlob(workerFn); | |||||
this.worker = new Worker(URL.createObjectURL(blob)); | |||||
} | |||||
else { | |||||
this.worker = new Worker(this.workerUrl); | |||||
} | |||||
// Post Message Polyfill | |||||
this.worker.postMessage = | |||||
this.worker.webkitPostMessage || this.worker.postMessage; | |||||
} | |||||
else { | |||||
eval(workerFn); | |||||
} | |||||
// Worker message receiver | |||||
this.msgName = (this.worker) ? 'message' : 'newCoords'; | |||||
this.listener = function(e) { | |||||
// Retrieving data | |||||
_this.nodesByteArray = new Float32Array(e.data.nodes); | |||||
// If ForceAtlas2 is running, we act accordingly | |||||
if (_this.running) { | |||||
// Applying layout | |||||
_this.applyLayoutChanges(); | |||||
// Send data back to worker and loop | |||||
_this.sendByteArrayToWorker(); | |||||
// Rendering graph | |||||
_this.sigInst.refresh(); | |||||
} | |||||
}; | |||||
(this.worker || document).addEventListener(this.msgName, this.listener); | |||||
// Filling byteArrays | |||||
this.graphToByteArrays(); | |||||
// Binding on kill to properly terminate layout when parent is killed | |||||
sigInst.bind('kill', function() { | |||||
sigInst.killForceAtlas2(); | |||||
}); | |||||
} | |||||
Supervisor.prototype.makeBlob = function(workerFn) { | |||||
var blob; | |||||
try { | |||||
blob = new Blob([workerFn], {type: 'application/javascript'}); | |||||
} | |||||
catch (e) { | |||||
_root.BlobBuilder = _root.BlobBuilder || | |||||
_root.WebKitBlobBuilder || | |||||
_root.MozBlobBuilder; | |||||
blob = new BlobBuilder(); | |||||
blob.append(workerFn); | |||||
blob = blob.getBlob(); | |||||
} | |||||
return blob; | |||||
}; | |||||
Supervisor.prototype.graphToByteArrays = function() { | |||||
var nodes = this.graph.nodes(), | |||||
edges = this.graph.edges(), | |||||
nbytes = nodes.length * this.ppn, | |||||
ebytes = edges.length * this.ppe, | |||||
nIndex = {}, | |||||
i, | |||||
j, | |||||
l; | |||||
// Allocating Byte arrays with correct nb of bytes | |||||
this.nodesByteArray = new Float32Array(nbytes); | |||||
this.edgesByteArray = new Float32Array(ebytes); | |||||
// Iterate through nodes | |||||
for (i = j = 0, l = nodes.length; i < l; i++) { | |||||
// Populating index | |||||
nIndex[nodes[i].id] = j; | |||||
// Populating byte array | |||||
this.nodesByteArray[j] = nodes[i].x; | |||||
this.nodesByteArray[j + 1] = nodes[i].y; | |||||
this.nodesByteArray[j + 2] = 0; | |||||
this.nodesByteArray[j + 3] = 0; | |||||
this.nodesByteArray[j + 4] = 0; | |||||
this.nodesByteArray[j + 5] = 0; | |||||
this.nodesByteArray[j + 6] = 1 + this.graph.degree(nodes[i].id); | |||||
this.nodesByteArray[j + 7] = 1; | |||||
this.nodesByteArray[j + 8] = nodes[i].size; | |||||
this.nodesByteArray[j + 9] = 0; | |||||
j += this.ppn; | |||||
} | |||||
// Iterate through edges | |||||
for (i = j = 0, l = edges.length; i < l; i++) { | |||||
this.edgesByteArray[j] = nIndex[edges[i].source]; | |||||
this.edgesByteArray[j + 1] = nIndex[edges[i].target]; | |||||
this.edgesByteArray[j + 2] = edges[i].weight || 0; | |||||
j += this.ppe; | |||||
} | |||||
}; | |||||
// TODO: make a better send function | |||||
Supervisor.prototype.applyLayoutChanges = function() { | |||||
var nodes = this.graph.nodes(), | |||||
j = 0, | |||||
realIndex; | |||||
// Moving nodes | |||||
for (var i = 0, l = this.nodesByteArray.length; i < l; i += this.ppn) { | |||||
nodes[j].x = this.nodesByteArray[i]; | |||||
nodes[j].y = this.nodesByteArray[i + 1]; | |||||
j++; | |||||
} | |||||
}; | |||||
Supervisor.prototype.sendByteArrayToWorker = function(action) { | |||||
var content = { | |||||
action: action || 'loop', | |||||
nodes: this.nodesByteArray.buffer | |||||
}; | |||||
var buffers = [this.nodesByteArray.buffer]; | |||||
if (action === 'start') { | |||||
content.config = this.config || {}; | |||||
content.edges = this.edgesByteArray.buffer; | |||||
buffers.push(this.edgesByteArray.buffer); | |||||
} | |||||
if (this.shouldUseWorker) | |||||
this.worker.postMessage(content, buffers); | |||||
else | |||||
_root.postMessage(content, '*'); | |||||
}; | |||||
Supervisor.prototype.start = function() { | |||||
if (this.running) | |||||
return; | |||||
this.running = true; | |||||
// Do not refresh edgequadtree during layout: | |||||
var k, | |||||
c; | |||||
for (k in this.sigInst.cameras) { | |||||
c = this.sigInst.cameras[k]; | |||||
c.edgequadtree._enabled = false; | |||||
} | |||||
if (!this.started) { | |||||
// Sending init message to worker | |||||
this.sendByteArrayToWorker('start'); | |||||
this.started = true; | |||||
} | |||||
else { | |||||
this.sendByteArrayToWorker(); | |||||
} | |||||
}; | |||||
Supervisor.prototype.stop = function() { | |||||
if (!this.running) | |||||
return; | |||||
// Allow to refresh edgequadtree: | |||||
var k, | |||||
c, | |||||
bounds; | |||||
for (k in this.sigInst.cameras) { | |||||
c = this.sigInst.cameras[k]; | |||||
c.edgequadtree._enabled = true; | |||||
// Find graph boundaries: | |||||
bounds = sigma.utils.getBoundaries( | |||||
this.graph, | |||||
c.readPrefix | |||||
); | |||||
// Refresh edgequadtree: | |||||
if (c.settings('drawEdges') && c.settings('enableEdgeHovering')) | |||||
c.edgequadtree.index(this.sigInst.graph, { | |||||
prefix: c.readPrefix, | |||||
bounds: { | |||||
x: bounds.minX, | |||||
y: bounds.minY, | |||||
width: bounds.maxX - bounds.minX, | |||||
height: bounds.maxY - bounds.minY | |||||
} | |||||
}); | |||||
} | |||||
this.running = false; | |||||
}; | |||||
Supervisor.prototype.killWorker = function() { | |||||
if (this.worker) { | |||||
this.worker.terminate(); | |||||
} | |||||
else { | |||||
_root.postMessage({action: 'kill'}, '*'); | |||||
document.removeEventListener(this.msgName, this.listener); | |||||
} | |||||
}; | |||||
Supervisor.prototype.configure = function(config) { | |||||
// Setting configuration | |||||
this.config = config; | |||||
if (!this.started) | |||||
return; | |||||
var data = {action: 'config', config: this.config}; | |||||
if (this.shouldUseWorker) | |||||
this.worker.postMessage(data); | |||||
else | |||||
_root.postMessage(data, '*'); | |||||
}; | |||||
/** | |||||
* Interface | |||||
* ---------- | |||||
*/ | |||||
sigma.prototype.startForceAtlas2 = function(config) { | |||||
// Create supervisor if undefined | |||||
if (!this.supervisor) | |||||
this.supervisor = new Supervisor(this, config); | |||||
// Configuration provided? | |||||
if (config) | |||||
this.supervisor.configure(config); | |||||
// Start algorithm | |||||
this.supervisor.start(); | |||||
return this; | |||||
}; | |||||
sigma.prototype.stopForceAtlas2 = function() { | |||||
if (!this.supervisor) | |||||
return this; | |||||
// Pause algorithm | |||||
this.supervisor.stop(); | |||||
return this; | |||||
}; | |||||
sigma.prototype.killForceAtlas2 = function() { | |||||
if (!this.supervisor) | |||||
return this; | |||||
// Stop Algorithm | |||||
this.supervisor.stop(); | |||||
// Kill Worker | |||||
this.supervisor.killWorker(); | |||||
// Kill supervisor | |||||
this.supervisor = null; | |||||
return this; | |||||
}; | |||||
sigma.prototype.configForceAtlas2 = function(config) { | |||||
if (!this.supervisor) | |||||
this.supervisor = new Supervisor(this, config); | |||||
this.supervisor.configure(config); | |||||
return this; | |||||
}; | |||||
sigma.prototype.isForceAtlas2Running = function(config) { | |||||
return !!this.supervisor && this.supervisor.running; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,127 @@ | |||||
/* | |||||
* grunt-forceAtlas2 | |||||
* | |||||
* This task crush and minify Force Atlas 2 code. | |||||
*/ | |||||
var uglify = require('uglify-js'); | |||||
// Shorteners | |||||
function minify(string) { | |||||
return uglify.minify(string, {fromString: true}).code; | |||||
} | |||||
// Crushing function | |||||
function crush(fnString) { | |||||
var pattern, | |||||
i, | |||||
l; | |||||
var np = [ | |||||
'x', | |||||
'y', | |||||
'dx', | |||||
'dy', | |||||
'old_dx', | |||||
'old_dy', | |||||
'mass', | |||||
'convergence', | |||||
'size', | |||||
'fixed' | |||||
]; | |||||
var ep = [ | |||||
'source', | |||||
'target', | |||||
'weight' | |||||
]; | |||||
var rp = [ | |||||
'node', | |||||
'centerX', | |||||
'centerY', | |||||
'size', | |||||
'nextSibling', | |||||
'firstChild', | |||||
'mass', | |||||
'massCenterX', | |||||
'massCenterY' | |||||
]; | |||||
// Replacing matrix accessors by incremented indexes | |||||
for (i = 0, l = rp.length; i < l; i++) { | |||||
pattern = new RegExp('rp\\(([^,]*), \'' + rp[i] + '\'\\)', 'g'); | |||||
fnString = fnString.replace( | |||||
pattern, | |||||
(i === 0) ? '$1' : '$1 + ' + i | |||||
); | |||||
} | |||||
for (i = 0, l = np.length; i < l; i++) { | |||||
pattern = new RegExp('np\\(([^,]*), \'' + np[i] + '\'\\)', 'g'); | |||||
fnString = fnString.replace( | |||||
pattern, | |||||
(i === 0) ? '$1' : '$1 + ' + i | |||||
); | |||||
} | |||||
for (i = 0, l = ep.length; i < l; i++) { | |||||
pattern = new RegExp('ep\\(([^,]*), \'' + ep[i] + '\'\\)', 'g'); | |||||
fnString = fnString.replace( | |||||
pattern, | |||||
(i === 0) ? '$1' : '$1 + ' + i | |||||
); | |||||
} | |||||
return fnString; | |||||
} | |||||
// Cleaning function | |||||
function clean(string) { | |||||
return string.replace( | |||||
/function crush\(fnString\)/, | |||||
'var crush = null; function no_crush(fnString)' | |||||
); | |||||
} | |||||
module.exports = function(grunt) { | |||||
// Force atlas grunt multitask | |||||
function multitask() { | |||||
// Merge task-specific and/or target-specific options with these defaults. | |||||
var options = this.options({}); | |||||
// Iterate over all specified file groups. | |||||
this.files.forEach(function(f) { | |||||
// Concat specified files. | |||||
var src = f.src.filter(function(filepath) { | |||||
// Warn on and remove invalid source files (if nonull was set). | |||||
if (!grunt.file.exists(filepath)) { | |||||
grunt.log.warn('Source file "' + filepath + '" not found.'); | |||||
return false; | |||||
} else { | |||||
return true; | |||||
} | |||||
}).map(function(filepath) { | |||||
// Read file source. | |||||
return grunt.file.read(filepath); | |||||
}).join('\n'); | |||||
// Crushing, cleaning and minifying | |||||
src = minify(clean(crush(src))); | |||||
// Write the destination file. | |||||
grunt.file.write(f.dest, src); | |||||
// Print a success message. | |||||
grunt.log.writeln('File "' + f.dest + '" created.'); | |||||
}); | |||||
} | |||||
// Registering the task | |||||
grunt.registerMultiTask( | |||||
'forceAtlas2', | |||||
'A grunt task to crush and minify ForceAtlas2.', | |||||
multitask | |||||
); | |||||
}; |
@ -0,0 +1,87 @@ | |||||
sigma.layout.noverlap | |||||
======================== | |||||
Plugin developed by [Andrew Pitts](https://github.com/apitts) and published under the [MIT](LICENSE) license. Original algorithm by [Mathieu Jacomy](https://github.com/jacomyma) and ported to sigma.js with permission. | |||||
--- | |||||
This plugin runs an algorithm which distributes nodes in the network, ensuring that they do not overlap and providing a margin where specified. | |||||
## Methods | |||||
**configure** | |||||
Changes the layout's configuration. | |||||
```js | |||||
var listener = s.configNoverlap(config); | |||||
``` | |||||
**start** | |||||
Starts the layout. It is possible to pass a configuration if this is the first time you start the layout. | |||||
```js | |||||
s.startNoverlap(); | |||||
``` | |||||
**isRunning** | |||||
Returns whether the layout is running. | |||||
```js | |||||
s.isNoverlapRunning(); | |||||
``` | |||||
## Configuration | |||||
* **nodes**: *array*: the subset of nodes to apply the layout. | |||||
*Algorithm configuration* | |||||
* **nodeMargin**: *number* `5.0`: The additional minimum space to apply around each and every node. | |||||
* **scaleNodes**: *number* `1.2`: A multiplier to apply to nodes such that larger nodes will have more space around them if this multiplier is greater than zero. | |||||
* **gridSize**: *integer* `20`: The number of rows and columns to use when dividing the nodes up into cells which the algorithm is applied to. Use more rows and columns for larger graphs for a more efficient algorithm. | |||||
* **permittedExpansion** *number* `1.1`: At every step, this is the maximum ratio to apply to the bounding box, i.e. the maximum by which the network is permitted to expand. | |||||
* **rendererIndex** *integer* `0`: The index of the renderer to use to compute overlap and collisions of the nodes. | |||||
* **speed** *number* `2`: A larger value increases the speed with which the algorithm will convergence at the cost of precision. | |||||
* **maxIterations** *number* `500`: The maximum number of iterations to run the algorithm for before stopping it. | |||||
*Easing configuration* | |||||
* **easing** *string*: if specified, ease the transition between nodes positions if background is `true`. The duration is specified by the Sigma settings `animationsTime`. See [sigma.utils.easing](../../src/utils/sigma.utils.js#L723) for available values. | |||||
* **duration** *number*: duration of the transition for the easing method. Default value is Sigma setting `animationsTime`. | |||||
## Events | |||||
The plugin dispatches the following events: | |||||
- `start`: on layout start. | |||||
- `interpolate`: at the beginning of the layout animation if an *easing* function is specified and the layout is ran on background. | |||||
- `stop`: on layout stop, will be dispatched after `interpolate`. | |||||
Example: | |||||
```js | |||||
s = new sigma({ | |||||
graph: g, | |||||
container: 'graph-container' | |||||
}); | |||||
var config = { | |||||
nodeMargin: 3.0, | |||||
scaleNodes: 1.3 | |||||
}; | |||||
// Configure the algorithm | |||||
var listener = s.configNoverlap(config); | |||||
// Bind all events: | |||||
listener.bind('start stop interpolate', function(event) { | |||||
console.log(event.type); | |||||
}); | |||||
// Start the algorithm: | |||||
s.startNoverlap(); | |||||
``` |
@ -0,0 +1,408 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw new Error('sigma is not declared'); | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.layout.noverlap'); | |||||
/** | |||||
* Noverlap Layout | |||||
* =============================== | |||||
* | |||||
* Author: @apitts / Andrew Pitts | |||||
* Algorithm: @jacomyma / Mathieu Jacomy (originally contributed to Gephi and ported to sigma.js under the MIT license by @andpitts with permission) | |||||
* Acknowledgement: @sheyman / Sébastien Heymann (some inspiration has been taken from other MIT licensed layout algorithms authored by @sheyman) | |||||
* Version: 0.1 | |||||
*/ | |||||
var settings = { | |||||
speed: 3, | |||||
scaleNodes: 1.2, | |||||
nodeMargin: 5.0, | |||||
gridSize: 20, | |||||
permittedExpansion: 1.1, | |||||
rendererIndex: 0, | |||||
maxIterations: 500 | |||||
}; | |||||
var _instance = {}; | |||||
/** | |||||
* Event emitter Object | |||||
* ------------------ | |||||
*/ | |||||
var _eventEmitter = {}; | |||||
/** | |||||
* Noverlap Object | |||||
* ------------------ | |||||
*/ | |||||
function Noverlap() { | |||||
var self = this; | |||||
this.init = function (sigInst, options) { | |||||
options = options || {}; | |||||
// Properties | |||||
this.sigInst = sigInst; | |||||
this.config = sigma.utils.extend(options, settings); | |||||
this.easing = options.easing; | |||||
this.duration = options.duration; | |||||
if (options.nodes) { | |||||
this.nodes = options.nodes; | |||||
delete options.nodes; | |||||
} | |||||
if (!sigma.plugins || typeof sigma.plugins.animate === 'undefined') { | |||||
throw new Error('sigma.plugins.animate is not declared'); | |||||
} | |||||
// State | |||||
this.running = false; | |||||
}; | |||||
/** | |||||
* Single layout iteration. | |||||
*/ | |||||
this.atomicGo = function () { | |||||
if (!this.running || this.iterCount < 1) return false; | |||||
var nodes = this.nodes || this.sigInst.graph.nodes(), | |||||
nodesCount = nodes.length, | |||||
i, | |||||
n, | |||||
n1, | |||||
n2, | |||||
xmin = Infinity, | |||||
xmax = -Infinity, | |||||
ymin = Infinity, | |||||
ymax = -Infinity, | |||||
xwidth, | |||||
yheight, | |||||
xcenter, | |||||
ycenter, | |||||
grid, | |||||
row, | |||||
col, | |||||
minXBox, | |||||
maxXBox, | |||||
minYBox, | |||||
maxYBox, | |||||
adjacentNodes, | |||||
subRow, | |||||
subCol, | |||||
nxmin, | |||||
nxmax, | |||||
nymin, | |||||
nymax; | |||||
this.iterCount--; | |||||
this.running = false; | |||||
for (i=0; i < nodesCount; i++) { | |||||
n = nodes[i]; | |||||
n.dn.dx = 0; | |||||
n.dn.dy = 0; | |||||
//Find the min and max for both x and y across all nodes | |||||
xmin = Math.min(xmin, n.dn_x - (n.dn_size*self.config.scaleNodes + self.config.nodeMargin) ); | |||||
xmax = Math.max(xmax, n.dn_x + (n.dn_size*self.config.scaleNodes + self.config.nodeMargin) ); | |||||
ymin = Math.min(ymin, n.dn_y - (n.dn_size*self.config.scaleNodes + self.config.nodeMargin) ); | |||||
ymax = Math.max(ymax, n.dn_y + (n.dn_size*self.config.scaleNodes + self.config.nodeMargin) ); | |||||
} | |||||
xwidth = xmax - xmin; | |||||
yheight = ymax - ymin; | |||||
xcenter = (xmin + xmax) / 2; | |||||
ycenter = (ymin + ymax) / 2; | |||||
xmin = xcenter - self.config.permittedExpansion*xwidth / 2; | |||||
xmax = xcenter + self.config.permittedExpansion*xwidth / 2; | |||||
ymin = ycenter - self.config.permittedExpansion*yheight / 2; | |||||
ymax = ycenter + self.config.permittedExpansion*yheight / 2; | |||||
grid = {}; //An object of objects where grid[row][col] is an array of node ids representing nodes that fall in that grid. Nodes can fall in more than one grid | |||||
for(row = 0; row < self.config.gridSize; row++) { | |||||
grid[row] = {}; | |||||
for(col = 0; col < self.config.gridSize; col++) { | |||||
grid[row][col] = []; | |||||
} | |||||
} | |||||
//Place nodes in grid | |||||
for (i=0; i < nodesCount; i++) { | |||||
n = nodes[i]; | |||||
nxmin = n.dn_x - (n.dn_size*self.config.scaleNodes + self.config.nodeMargin); | |||||
nxmax = n.dn_x + (n.dn_size*self.config.scaleNodes + self.config.nodeMargin); | |||||
nymin = n.dn_y - (n.dn_size*self.config.scaleNodes + self.config.nodeMargin); | |||||
nymax = n.dn_y + (n.dn_size*self.config.scaleNodes + self.config.nodeMargin); | |||||
minXBox = Math.floor(self.config.gridSize* (nxmin - xmin) / (xmax - xmin) ); | |||||
maxXBox = Math.floor(self.config.gridSize* (nxmax - xmin) / (xmax - xmin) ); | |||||
minYBox = Math.floor(self.config.gridSize* (nymin - ymin) / (ymax - ymin) ); | |||||
maxYBox = Math.floor(self.config.gridSize* (nymax - ymin) / (ymax - ymin) ); | |||||
for(col = minXBox; col <= maxXBox; col++) { | |||||
for(row = minYBox; row <= maxYBox; row++) { | |||||
grid[row][col].push(n.id); | |||||
} | |||||
} | |||||
} | |||||
adjacentNodes = {}; //An object that stores the node ids of adjacent nodes (either in same grid box or adjacent grid box) for all nodes | |||||
for(row = 0; row < self.config.gridSize; row++) { | |||||
for(col = 0; col < self.config.gridSize; col++) { | |||||
grid[row][col].forEach(function(nodeId) { | |||||
if(!adjacentNodes[nodeId]) { | |||||
adjacentNodes[nodeId] = []; | |||||
} | |||||
for(subRow = Math.max(0, row - 1); subRow <= Math.min(row + 1, self.config.gridSize - 1); subRow++) { | |||||
for(subCol = Math.max(0, col - 1); subCol <= Math.min(col + 1, self.config.gridSize - 1); subCol++) { | |||||
grid[subRow][subCol].forEach(function(subNodeId) { | |||||
if(subNodeId !== nodeId && adjacentNodes[nodeId].indexOf(subNodeId) === -1) { | |||||
adjacentNodes[nodeId].push(subNodeId); | |||||
} | |||||
}); | |||||
} | |||||
} | |||||
}); | |||||
} | |||||
} | |||||
//If two nodes overlap then repulse them | |||||
for (i=0; i < nodesCount; i++) { | |||||
n1 = nodes[i]; | |||||
adjacentNodes[n1.id].forEach(function(nodeId) { | |||||
var n2 = self.sigInst.graph.nodes(nodeId); | |||||
var xDist = n2.dn_x - n1.dn_x; | |||||
var yDist = n2.dn_y - n1.dn_y; | |||||
var dist = Math.sqrt(xDist*xDist + yDist*yDist); | |||||
var collision = (dist < ((n1.dn_size*self.config.scaleNodes + self.config.nodeMargin) + (n2.dn_size*self.config.scaleNodes + self.config.nodeMargin))); | |||||
if(collision) { | |||||
self.running = true; | |||||
if(dist > 0) { | |||||
n2.dn.dx += xDist / dist * (1 + n1.dn_size); | |||||
n2.dn.dy += yDist / dist * (1 + n1.dn_size); | |||||
} else { | |||||
n2.dn.dx += xwidth * 0.01 * (0.5 - Math.random()); | |||||
n2.dn.dy += yheight * 0.01 * (0.5 - Math.random()); | |||||
} | |||||
} | |||||
}); | |||||
} | |||||
for (i=0; i < nodesCount; i++) { | |||||
n = nodes[i]; | |||||
if(!n.fixed) { | |||||
n.dn_x = n.dn_x + n.dn.dx * 0.1 * self.config.speed; | |||||
n.dn_y = n.dn_y + n.dn.dy * 0.1 * self.config.speed; | |||||
} | |||||
} | |||||
if(this.running && this.iterCount < 1) { | |||||
this.running = false; | |||||
} | |||||
return this.running; | |||||
}; | |||||
this.go = function () { | |||||
this.iterCount = this.config.maxIterations; | |||||
while (this.running) { | |||||
this.atomicGo(); | |||||
}; | |||||
this.stop(); | |||||
}; | |||||
this.start = function() { | |||||
if (this.running) return; | |||||
var nodes = this.sigInst.graph.nodes(); | |||||
var prefix = this.sigInst.renderers[self.config.rendererIndex].options.prefix; | |||||
this.running = true; | |||||
// Init nodes | |||||
for (var i = 0; i < nodes.length; i++) { | |||||
nodes[i].dn_x = nodes[i][prefix + 'x']; | |||||
nodes[i].dn_y = nodes[i][prefix + 'y']; | |||||
nodes[i].dn_size = nodes[i][prefix + 'size']; | |||||
nodes[i].dn = { | |||||
dx: 0, | |||||
dy: 0 | |||||
}; | |||||
} | |||||
_eventEmitter[self.sigInst.id].dispatchEvent('start'); | |||||
this.go(); | |||||
}; | |||||
this.stop = function() { | |||||
var nodes = this.sigInst.graph.nodes(); | |||||
this.running = false; | |||||
if (this.easing) { | |||||
_eventEmitter[self.sigInst.id].dispatchEvent('interpolate'); | |||||
sigma.plugins.animate( | |||||
self.sigInst, | |||||
{ | |||||
x: 'dn_x', | |||||
y: 'dn_y' | |||||
}, | |||||
{ | |||||
easing: self.easing, | |||||
onComplete: function() { | |||||
self.sigInst.refresh(); | |||||
for (var i = 0; i < nodes.length; i++) { | |||||
nodes[i].dn = null; | |||||
nodes[i].dn_x = null; | |||||
nodes[i].dn_y = null; | |||||
} | |||||
_eventEmitter[self.sigInst.id].dispatchEvent('stop'); | |||||
}, | |||||
duration: self.duration | |||||
} | |||||
); | |||||
} | |||||
else { | |||||
// Apply changes | |||||
for (var i = 0; i < nodes.length; i++) { | |||||
nodes[i].x = nodes[i].dn_x; | |||||
nodes[i].y = nodes[i].dn_y; | |||||
} | |||||
this.sigInst.refresh(); | |||||
for (var i = 0; i < nodes.length; i++) { | |||||
nodes[i].dn = null; | |||||
nodes[i].dn_x = null; | |||||
nodes[i].dn_y = null; | |||||
} | |||||
_eventEmitter[self.sigInst.id].dispatchEvent('stop'); | |||||
} | |||||
}; | |||||
this.kill = function() { | |||||
this.sigInst = null; | |||||
this.config = null; | |||||
this.easing = null; | |||||
}; | |||||
}; | |||||
/** | |||||
* Interface | |||||
* ---------- | |||||
*/ | |||||
/** | |||||
* Configure the layout algorithm. | |||||
* Recognized options: | |||||
* ********************** | |||||
* Here is the exhaustive list of every accepted parameter in the settings | |||||
* object: | |||||
* | |||||
* {?number} speed A larger value increases the convergence speed at the cost of precision | |||||
* {?number} scaleNodes The ratio to scale nodes by - a larger ratio will lead to more space around larger nodes | |||||
* {?number} nodeMargin A fixed margin to apply around nodes regardless of size | |||||
* {?number} maxIterations The maximum number of iterations to perform before the layout completes. | |||||
* {?integer} gridSize The number of rows and columns to use when partioning nodes into a grid for efficient computation | |||||
* {?number} permittedExpansion A permitted expansion factor to the overall size of the network applied at each iteration | |||||
* {?integer} rendererIndex The index of the renderer to use for node co-ordinates. Defaults to zero. | |||||
* {?(function|string)} easing Either the name of an easing in the sigma.utils.easings package or a function. If not specified, the | |||||
* quadraticInOut easing from this package will be used instead. | |||||
* {?number} duration The duration of the animation. If not specified, the "animationsTime" setting value of the sigma instance will be used instead. | |||||
* | |||||
* | |||||
* @param {object} config The optional configuration object. | |||||
* | |||||
* @return {sigma.classes.dispatcher} Returns an event emitter. | |||||
*/ | |||||
sigma.prototype.configNoverlap = function(config) { | |||||
var sigInst = this; | |||||
if (!config) throw new Error('Missing argument: "config"'); | |||||
// Create instance if undefined | |||||
if (!_instance[sigInst.id]) { | |||||
_instance[sigInst.id] = new Noverlap(); | |||||
_eventEmitter[sigInst.id] = {}; | |||||
sigma.classes.dispatcher.extend(_eventEmitter[sigInst.id]); | |||||
// Binding on kill to clear the references | |||||
sigInst.bind('kill', function() { | |||||
_instance[sigInst.id].kill(); | |||||
_instance[sigInst.id] = null; | |||||
_eventEmitter[sigInst.id] = null; | |||||
}); | |||||
} | |||||
_instance[sigInst.id].init(sigInst, config); | |||||
return _eventEmitter[sigInst.id]; | |||||
}; | |||||
/** | |||||
* Start the layout algorithm. It will use the existing configuration if no | |||||
* new configuration is passed. | |||||
* Recognized options: | |||||
* ********************** | |||||
* Here is the exhaustive list of every accepted parameter in the settings | |||||
* object | |||||
* | |||||
* {?number} speed A larger value increases the convergence speed at the cost of precision | |||||
* {?number} scaleNodes The ratio to scale nodes by - a larger ratio will lead to more space around larger nodes | |||||
* {?number} nodeMargin A fixed margin to apply around nodes regardless of size | |||||
* {?number} maxIterations The maximum number of iterations to perform before the layout completes. | |||||
* {?integer} gridSize The number of rows and columns to use when partioning nodes into a grid for efficient computation | |||||
* {?number} permittedExpansion A permitted expansion factor to the overall size of the network applied at each iteration | |||||
* {?integer} rendererIndex The index of the renderer to use for node co-ordinates. Defaults to zero. | |||||
* {?(function|string)} easing Either the name of an easing in the sigma.utils.easings package or a function. If not specified, the | |||||
* quadraticInOut easing from this package will be used instead. | |||||
* {?number} duration The duration of the animation. If not specified, the "animationsTime" setting value of the sigma instance will be used instead. | |||||
* | |||||
* | |||||
* | |||||
* @param {object} config The optional configuration object. | |||||
* | |||||
* @return {sigma.classes.dispatcher} Returns an event emitter. | |||||
*/ | |||||
sigma.prototype.startNoverlap = function(config) { | |||||
var sigInst = this; | |||||
if (config) { | |||||
this.configNoverlap(sigInst, config); | |||||
} | |||||
_instance[sigInst.id].start(); | |||||
return _eventEmitter[sigInst.id]; | |||||
}; | |||||
/** | |||||
* Returns true if the layout has started and is not completed. | |||||
* | |||||
* @return {boolean} | |||||
*/ | |||||
sigma.prototype.isNoverlapRunning = function() { | |||||
var sigInst = this; | |||||
return !!_instance[sigInst.id] && _instance[sigInst.id].running; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,553 @@ | |||||
GNU GENERAL PUBLIC LICENSE | |||||
Version 3, 29 June 2007 | |||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> | |||||
Everyone is permitted to copy and distribute verbatim copies | |||||
of this license document, but changing it is not allowed. | |||||
Preamble | |||||
The GNU General Public License is a free, copyleft license for | |||||
software and other kinds of works. | |||||
The licenses for most software and other practical works are designed | |||||
to take away your freedom to share and change the works. By contrast, | |||||
the GNU General Public License is intended to guarantee your freedom to | |||||
share and change all versions of a program--to make sure it remains free | |||||
software for all its users. We, the Free Software Foundation, use the | |||||
GNU General Public License for most of our software; it applies also to | |||||
any other work released this way by its authors. You can apply it to | |||||
your programs, too. | |||||
When we speak of free software, we are referring to freedom, not | |||||
price. Our General Public Licenses are designed to make sure that you | |||||
have the freedom to distribute copies of free software (and charge for | |||||
them if you wish), that you receive source code or can get it if you | |||||
want it, that you can change the software or use pieces of it in new | |||||
free programs, and that you know you can do these things. | |||||
To protect your rights, we need to prevent others from denying you | |||||
these rights or asking you to surrender the rights. Therefore, you have | |||||
certain responsibilities if you distribute copies of the software, or if | |||||
you modify it: responsibilities to respect the freedom of others. | |||||
For example, if you distribute copies of such a program, whether | |||||
gratis or for a fee, you must pass on to the recipients the same | |||||
freedoms that you received. You must make sure that they, too, receive | |||||
or can get the source code. And you must show them these terms so they | |||||
know their rights. | |||||
Developers that use the GNU GPL protect your rights with two steps: | |||||
(1) assert copyright on the software, and (2) offer you this License | |||||
giving you legal permission to copy, distribute and/or modify it. | |||||
For the developers' and authors' protection, the GPL clearly explains | |||||
that there is no warranty for this free software. For both users' and | |||||
authors' sake, the GPL requires that modified versions be marked as | |||||
changed, so that their problems will not be attributed erroneously to | |||||
authors of previous versions. | |||||
Some devices are designed to deny users access to install or run | |||||
modified versions of the software inside them, although the manufacturer | |||||
can do so. This is fundamentally incompatible with the aim of | |||||
protecting users' freedom to change the software. The systematic | |||||
pattern of such abuse occurs in the area of products for individuals to | |||||
use, which is precisely where it is most unacceptable. Therefore, we | |||||
have designed this version of the GPL to prohibit the practice for those | |||||
products. If such problems arise substantially in other domains, we | |||||
stand ready to extend this provision to those domains in future versions | |||||
of the GPL, as needed to protect the freedom of users. | |||||
Finally, every program is threatened constantly by software patents. | |||||
States should not allow patents to restrict development and use of | |||||
software on general-purpose computers, but in those that do, we wish to | |||||
avoid the special danger that patents applied to a free program could | |||||
make it effectively proprietary. To prevent this, the GPL assures that | |||||
patents cannot be used to render the program non-free. | |||||
The precise terms and conditions for copying, distribution and | |||||
modification follow. | |||||
TERMS AND CONDITIONS | |||||
0. Definitions. | |||||
"This License" refers to version 3 of the GNU General Public License. | |||||
"Copyright" also means copyright-like laws that apply to other kinds of | |||||
works, such as semiconductor masks. | |||||
"The Program" refers to any copyrightable work licensed under this | |||||
License. Each licensee is addressed as "you". "Licensees" and | |||||
"recipients" may be individuals or organizations. | |||||
To "modify" a work means to copy from or adapt all or part of the work | |||||
in a fashion requiring copyright permission, other than the making of an | |||||
exact copy. The resulting work is called a "modified version" of the | |||||
earlier work or a work "based on" the earlier work. | |||||
A "covered work" means either the unmodified Program or a work based | |||||
on the Program. | |||||
To "propagate" a work means to do anything with it that, without | |||||
permission, would make you directly or secondarily liable for | |||||
infringement under applicable copyright law, except executing it on a | |||||
computer or modifying a private copy. Propagation includes copying, | |||||
distribution (with or without modification), making available to the | |||||
public, and in some countries other activities as well. | |||||
To "convey" a work means any kind of propagation that enables other | |||||
parties to make or receive copies. Mere interaction with a user through | |||||
a computer network, with no transfer of a copy, is not conveying. | |||||
An interactive user interface displays "Appropriate Legal Notices" | |||||
to the extent that it includes a convenient and prominently visible | |||||
feature that (1) displays an appropriate copyright notice, and (2) | |||||
tells the user that there is no warranty for the work (except to the | |||||
extent that warranties are provided), that licensees may convey the | |||||
work under this License, and how to view a copy of this License. If | |||||
the interface presents a list of user commands or options, such as a | |||||
menu, a prominent item in the list meets this criterion. | |||||
1. Source Code. | |||||
The "source code" for a work means the preferred form of the work | |||||
for making modifications to it. "Object code" means any non-source | |||||
form of a work. | |||||
A "Standard Interface" means an interface that either is an official | |||||
standard defined by a recognized standards body, or, in the case of | |||||
interfaces specified for a particular programming language, one that | |||||
is widely used among developers working in that language. | |||||
The "System Libraries" of an executable work include anything, other | |||||
than the work as a whole, that (a) is included in the normal form of | |||||
packaging a Major Component, but which is not part of that Major | |||||
Component, and (b) serves only to enable use of the work with that | |||||
Major Component, or to implement a Standard Interface for which an | |||||
implementation is available to the public in source code form. A | |||||
"Major Component", in this context, means a major essential component | |||||
(kernel, window system, and so on) of the specific operating system | |||||
(if any) on which the executable work runs, or a compiler used to | |||||
produce the work, or an object code interpreter used to run it. | |||||
The "Corresponding Source" for a work in object code form means all | |||||
the source code needed to generate, install, and (for an executable | |||||
work) run the object code and to modify the work, including scripts to | |||||
control those activities. However, it does not include the work's | |||||
System Libraries, or general-purpose tools or generally available free | |||||
programs which are used unmodified in performing those activities but | |||||
which are not part of the work. For example, Corresponding Source | |||||
includes interface definition files associated with source files for | |||||
the work, and the source code for shared libraries and dynamically | |||||
linked subprograms that the work is specifically designed to require, | |||||
such as by intimate data communication or control flow between those | |||||
subprograms and other parts of the work. | |||||
The Corresponding Source need not include anything that users | |||||
can regenerate automatically from other parts of the Corresponding | |||||
Source. | |||||
The Corresponding Source for a work in source code form is that | |||||
same work. | |||||
2. Basic Permissions. | |||||
All rights granted under this License are granted for the term of | |||||
copyright on the Program, and are irrevocable provided the stated | |||||
conditions are met. This License explicitly affirms your unlimited | |||||
permission to run the unmodified Program. The output from running a | |||||
covered work is covered by this License only if the output, given its | |||||
content, constitutes a covered work. This License acknowledges your | |||||
rights of fair use or other equivalent, as provided by copyright law. | |||||
You may make, run and propagate covered works that you do not | |||||
convey, without conditions so long as your license otherwise remains | |||||
in force. You may convey covered works to others for the sole purpose | |||||
of having them make modifications exclusively for you, or provide you | |||||
with facilities for running those works, provided that you comply with | |||||
the terms of this License in conveying all material for which you do | |||||
not control copyright. Those thus making or running the covered works | |||||
for you must do so exclusively on your behalf, under your direction | |||||
and control, on terms that prohibit them from making any copies of | |||||
your copyrighted material outside their relationship with you. | |||||
Conveying under any other circumstances is permitted solely under | |||||
the conditions stated below. Sublicensing is not allowed; section 10 | |||||
makes it unnecessary. | |||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law. | |||||
No covered work shall be deemed part of an effective technological | |||||
measure under any applicable law fulfilling obligations under article | |||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or | |||||
similar laws prohibiting or restricting circumvention of such | |||||
measures. | |||||
When you convey a covered work, you waive any legal power to forbid | |||||
circumvention of technological measures to the extent such circumvention | |||||
is effected by exercising rights under this License with respect to | |||||
the covered work, and you disclaim any intention to limit operation or | |||||
modification of the work as a means of enforcing, against the work's | |||||
users, your or third parties' legal rights to forbid circumvention of | |||||
technological measures. | |||||
4. Conveying Verbatim Copies. | |||||
You may convey verbatim copies of the Program's source code as you | |||||
receive it, in any medium, provided that you conspicuously and | |||||
appropriately publish on each copy an appropriate copyright notice; | |||||
keep intact all notices stating that this License and any | |||||
non-permissive terms added in accord with section 7 apply to the code; | |||||
keep intact all notices of the absence of any warranty; and give all | |||||
recipients a copy of this License along with the Program. | |||||
You may charge any price or no price for each copy that you convey, | |||||
and you may offer support or warranty protection for a fee. | |||||
5. Conveying Modified Source Versions. | |||||
You may convey a work based on the Program, or the modifications to | |||||
produce it from the Program, in the form of source code under the | |||||
terms of section 4, provided that you also meet all of these conditions: | |||||
a) The work must carry prominent notices stating that you modified | |||||
it, and giving a relevant date. | |||||
b) The work must carry prominent notices stating that it is | |||||
released under this License and any conditions added under section | |||||
7. This requirement modifies the requirement in section 4 to | |||||
"keep intact all notices". | |||||
c) You must license the entire work, as a whole, under this | |||||
License to anyone who comes into possession of a copy. This | |||||
License will therefore apply, along with any applicable section 7 | |||||
additional terms, to the whole of the work, and all its parts, | |||||
regardless of how they are packaged. This License gives no | |||||
permission to license the work in any other way, but it does not | |||||
invalidate such permission if you have separately received it. | |||||
d) If the work has interactive user interfaces, each must display | |||||
Appropriate Legal Notices; however, if the Program has interactive | |||||
interfaces that do not display Appropriate Legal Notices, your | |||||
work need not make them do so. | |||||
A compilation of a covered work with other separate and independent | |||||
works, which are not by their nature extensions of the covered work, | |||||
and which are not combined with it such as to form a larger program, | |||||
in or on a volume of a storage or distribution medium, is called an | |||||
"aggregate" if the compilation and its resulting copyright are not | |||||
used to limit the access or legal rights of the compilation's users | |||||
beyond what the individual works permit. Inclusion of a covered work | |||||
in an aggregate does not cause this License to apply to the other | |||||
parts of the aggregate. | |||||
6. Conveying Non-Source Forms. | |||||
You may convey a covered work in object code form under the terms | |||||
of sections 4 and 5, provided that you also convey the | |||||
machine-readable Corresponding Source under the terms of this License, | |||||
in one of these ways: | |||||
a) Convey the object code in, or embodied in, a physical product | |||||
(including a physical distribution medium), accompanied by the | |||||
Corresponding Source fixed on a durable physical medium | |||||
customarily used for software interchange. | |||||
b) Convey the object code in, or embodied in, a physical product | |||||
(including a physical distribution medium), accompanied by a | |||||
written offer, valid for at least three years and valid for as | |||||
long as you offer spare parts or customer support for that product | |||||
model, to give anyone who possesses the object code either (1) a | |||||
copy of the Corresponding Source for all the software in the | |||||
product that is covered by this License, on a durable physical | |||||
medium customarily used for software interchange, for a price no | |||||
more than your reasonable cost of physically performing this | |||||
conveying of source, or (2) access to copy the | |||||
Corresponding Source from a network server at no charge. | |||||
c) Convey individual copies of the object code with a copy of the | |||||
written offer to provide the Corresponding Source. This | |||||
alternative is allowed only occasionally and noncommercially, and | |||||
only if you received the object code with such an offer, in accord | |||||
with subsection 6b. | |||||
d) Convey the object code by offering access from a designated | |||||
place (gratis or for a charge), and offer equivalent access to the | |||||
Corresponding Source in the same way through the same place at no | |||||
further charge. You need not require recipients to copy the | |||||
Corresponding Source along with the object code. If the place to | |||||
copy the object code is a network server, the Corresponding Source | |||||
may be on a different server (operated by you or a third party) | |||||
that supports equivalent copying facilities, provided you maintain | |||||
clear directions next to the object code saying where to find the | |||||
Corresponding Source. Regardless of what server hosts the | |||||
Corresponding Source, you remain obligated to ensure that it is | |||||
available for as long as needed to satisfy these requirements. | |||||
e) Convey the object code using peer-to-peer transmission, provided | |||||
you inform other peers where the object code and Corresponding | |||||
Source of the work are being offered to the general public at no | |||||
charge under subsection 6d. | |||||
A separable portion of the object code, whose source code is excluded | |||||
from the Corresponding Source as a System Library, need not be | |||||
included in conveying the object code work. | |||||
A "User Product" is either (1) a "consumer product", which means any | |||||
tangible personal property which is normally used for personal, family, | |||||
or household purposes, or (2) anything designed or sold for incorporation | |||||
into a dwelling. In determining whether a product is a consumer product, | |||||
doubtful cases shall be resolved in favor of coverage. For a particular | |||||
product received by a particular user, "normally used" refers to a | |||||
typical or common use of that class of product, regardless of the status | |||||
of the particular user or of the way in which the particular user | |||||
actually uses, or expects or is expected to use, the product. A product | |||||
is a consumer product regardless of whether the product has substantial | |||||
commercial, industrial or non-consumer uses, unless such uses represent | |||||
the only significant mode of use of the product. | |||||
"Installation Information" for a User Product means any methods, | |||||
procedures, authorization keys, or other information required to install | |||||
and execute modified versions of a covered work in that User Product from | |||||
a modified version of its Corresponding Source. The information must | |||||
suffice to ensure that the continued functioning of the modified object | |||||
code is in no case prevented or interfered with solely because | |||||
modification has been made. | |||||
If you convey an object code work under this section in, or with, or | |||||
specifically for use in, a User Product, and the conveying occurs as | |||||
part of a transaction in which the right of possession and use of the | |||||
User Product is transferred to the recipient in perpetuity or for a | |||||
fixed term (regardless of how the transaction is characterized), the | |||||
Corresponding Source conveyed under this section must be accompanied | |||||
by the Installation Information. But this requirement does not apply | |||||
if neither you nor any third party retains the ability to install | |||||
modified object code on the User Product (for example, the work has | |||||
been installed in ROM). | |||||
The requirement to provide Installation Information does not include a | |||||
requirement to continue to provide support service, warranty, or updates | |||||
for a work that has been modified or installed by the recipient, or for | |||||
the User Product in which it has been modified or installed. Access to a | |||||
network may be denied when the modification itself materially and | |||||
adversely affects the operation of the network or violates the rules and | |||||
protocols for communication across the network. | |||||
Corresponding Source conveyed, and Installation Information provided, | |||||
in accord with this section must be in a format that is publicly | |||||
documented (and with an implementation available to the public in | |||||
source code form), and must require no special password or key for | |||||
unpacking, reading or copying. | |||||
7. Additional Terms. | |||||
"Additional permissions" are terms that supplement the terms of this | |||||
License by making exceptions from one or more of its conditions. | |||||
Additional permissions that are applicable to the entire Program shall | |||||
be treated as though they were included in this License, to the extent | |||||
that they are valid under applicable law. If additional permissions | |||||
apply only to part of the Program, that part may be used separately | |||||
under those permissions, but the entire Program remains governed by | |||||
this License without regard to the additional permissions. | |||||
When you convey a copy of a covered work, you may at your option | |||||
remove any additional permissions from that copy, or from any part of | |||||
it. (Additional permissions may be written to require their own | |||||
removal in certain cases when you modify the work.) You may place | |||||
additional permissions on material, added by you to a covered work, | |||||
for which you have or can give appropriate copyright permission. | |||||
Notwithstanding any other provision of this License, for material you | |||||
add to a covered work, you may (if authorized by the copyright holders of | |||||
that material) supplement the terms of this License with terms: | |||||
a) Disclaiming warranty or limiting liability differently from the | |||||
terms of sections 15 and 16 of this License; or | |||||
b) Requiring preservation of specified reasonable legal notices or | |||||
author attributions in that material or in the Appropriate Legal | |||||
Notices displayed by works containing it; or | |||||
c) Prohibiting misrepresentation of the origin of that material, or | |||||
requiring that modified versions of such material be marked in | |||||
reasonable ways as different from the original version; or | |||||
d) Limiting the use for publicity purposes of names of licensors or | |||||
authors of the material; or | |||||
e) Declining to grant rights under trademark law for use of some | |||||
trade names, trademarks, or service marks; or | |||||
f) Requiring indemnification of licensors and authors of that | |||||
material by anyone who conveys the material (or modified versions of | |||||
it) with contractual assumptions of liability to the recipient, for | |||||
any liability that these contractual assumptions directly impose on | |||||
those licensors and authors. | |||||
All other non-permissive additional terms are considered "further | |||||
restrictions" within the meaning of section 10. If the Program as you | |||||
received it, or any part of it, contains a notice stating that it is | |||||
governed by this License along with a term that is a further | |||||
restriction, you may remove that term. If a license document contains | |||||
a further restriction but permits relicensing or conveying under this | |||||
License, you may add to a covered work material governed by the terms | |||||
of that license document, provided that the further restriction does | |||||
not survive such relicensing or conveying. | |||||
If you add terms to a covered work in accord with this section, you | |||||
must place, in the relevant source files, a statement of the | |||||
additional terms that apply to those files, or a notice indicating | |||||
where to find the applicable terms. | |||||
Additional terms, permissive or non-permissive, may be stated in the | |||||
form of a separately written license, or stated as exceptions; | |||||
the above requirements apply either way. | |||||
8. Termination. | |||||
You may not propagate or modify a covered work except as expressly | |||||
provided under this License. Any attempt otherwise to propagate or | |||||
modify it is void, and will automatically terminate your rights under | |||||
this License (including any patent licenses granted under the third | |||||
paragraph of section 11). | |||||
However, if you cease all violation of this License, then your | |||||
license from a particular copyright holder is reinstated (a) | |||||
provisionally, unless and until the copyright holder explicitly and | |||||
finally terminates your license, and (b) permanently, if the copyright | |||||
holder fails to notify you of the violation by some reasonable means | |||||
prior to 60 days after the cessation. | |||||
Moreover, your license from a particular copyright holder is | |||||
reinstated permanently if the copyright holder notifies you of the | |||||
violation by some reasonable means, this is the first time you have | |||||
received notice of violation of this License (for any work) from that | |||||
copyright holder, and you cure the violation prior to 30 days after | |||||
your receipt of the notice. | |||||
Termination of your rights under this section does not terminate the | |||||
licenses of parties who have received copies or rights from you under | |||||
this License. If your rights have been terminated and not permanently | |||||
reinstated, you do not qualify to receive new licenses for the same | |||||
material under section 10. | |||||
9. Acceptance Not Required for Having Copies. | |||||
You are not required to accept this License in order to receive or | |||||
run a copy of the Program. Ancillary propagation of a covered work | |||||
occurring solely as a consequence of using peer-to-peer transmission | |||||
to receive a copy likewise does not require acceptance. However, | |||||
nothing other than this License grants you permission to propagate or | |||||
modify any covered work. These actions infringe copyright if you do | |||||
not accept this License. Therefore, by modifying or propagating a | |||||
covered work, you indicate your acceptance of this License to do so. | |||||
10. Automatic Licensing of Downstream Recipients. | |||||
Each time you convey a covered work, the recipient automatically | |||||
receives a license from the original licensors, to run, modify and | |||||
propagate that work, subject to this License. You are not responsible | |||||
for enforcing compliance by third parties with this License. | |||||
An "entity transaction" is a transaction transferring control of an | |||||
organization, or substantially all assets of one, or subdividing an | |||||
organization, or merging organizations. If propagation of a covered | |||||
work results from an entity transaction, each party to that | |||||
transaction who receives a copy of the work also receives whatever | |||||
licenses to the work the party's predecessor in interest had or could | |||||
give under the previous paragraph, plus a right to possession of the | |||||
Corresponding Source of the work from the predecessor in interest, if | |||||
the predecessor has it or can get it with reasonable efforts. | |||||
You may not impose any further restrictions on the exercise of the | |||||
rights granted or affirmed under this License. For example, you may | |||||
not impose a license fee, royalty, or other charge for exercise of | |||||
rights granted under this License, and you may not initiate litigation | |||||
(including a cross-claim or counterclaim in a lawsuit) alleging that | |||||
any patent claim is infringed by making, using, selling, offering for | |||||
sale, or importing the Program or any portion of it. | |||||
11. Patents. | |||||
A "contributor" is a copyright holder who authorizes use under this | |||||
License of the Program or a work on which the Program is based. The | |||||
work thus licensed is called the contributor's "contributor version". | |||||
A contributor's "essential patent claims" are all patent claims | |||||
owned or controlled by the contributor, whether already acquired or | |||||
hereafter acquired, that would be infringed by some manner, permitted | |||||
by this License, of making, using, or selling its contributor version, | |||||
but do not include claims that would be infringed only as a | |||||
consequence of further modification of the contributor version. For | |||||
purposes of this definition, "control" includes the right to grant | |||||
patent sublicenses in a manner consistent with the requirements of | |||||
this License. | |||||
Each contributor grants you a non-exclusive, worldwide, royalty-free | |||||
patent license under the contributor's essential patent claims, to | |||||
make, use, sell, offer for sale, import and otherwise run, modify and | |||||
propagate the contents of its contributor version. | |||||
In the following three paragraphs, a "patent license" is any express | |||||
agreement or commitment, however denominated, not to enforce a patent | |||||
(such as an express permission to practice a patent or covenant not to | |||||
sue for patent infringement). To "grant" such a patent license to a | |||||
party means to make such an agreement or commitment not to enforce a | |||||
patent against the party. | |||||
If you convey a covered work, knowingly relying on a patent license, | |||||
and the Corresponding Source of the work is not available for anyone | |||||
to copy, free of charge and under the terms of this License, through a | |||||
publicly available network server or other readily accessible means, | |||||
then you must either (1) cause the Corresponding Source to be so | |||||
available, or (2) arrange to deprive yourself of the benefit of the | |||||
patent license for this particular work, or (3) arrange, in a manner | |||||
consistent with the requirements of this License, to extend the patent | |||||
license to downstream recipients. "Knowingly relying" means you have | |||||
actual knowledge that, but for the patent license, your conveying the | |||||
covered work in a country, or your recipient's use of the covered work | |||||
in a country, would infringe one or more identifiable patents in that | |||||
country that you have reason to believe are valid. | |||||
If, pursuant to or in connection with a single transaction or | |||||
arrangement, you convey, or propagate by procuring conveyance of, a | |||||
covered work, and grant a patent license to some of the parties | |||||
receiving the covered work authorizing them to use, propagate, modify | |||||
or convey a specific copy of the covered work, then the patent license | |||||
you grant is automatically extended to all recipients of the covered | |||||
work and works based on it. | |||||
A patent license is "discriminatory" if it does not include within | |||||
the scope of its coverage, prohibits the exercise of, or is | |||||
conditioned on the non-exercise of one or more of the rights that are | |||||
specifically granted under this License. You may not convey a covered | |||||
work if you are a party to an arrangement with a third party that is | |||||
in the business of distributing software, under which you make payment | |||||
to the third party based on the extent of your activity of conveying | |||||
the work, and under which the third party grants, to any of the | |||||
parties who would receive the covered work from you, a discriminatory | |||||
patent license (a) in connection with copies of the covered work | |||||
conveyed by you (or copies made from those copies), or (b) primarily | |||||
for and in connection with specific products or compilations that | |||||
contain the covered work, unless you entered into that arrangement, | |||||
or that patent license was granted, prior to 28 March 2007. | |||||
Nothing in this License shall be construed as excluding or limiting | |||||
any implied license or other defenses to infringement that may | |||||
otherwise be available to you under applicable patent law. | |||||
12. No Surrender of Others' Freedom. | |||||
If conditions are imposed on you (whether by court order, agreement or | |||||
otherwise) that contradict the conditions of this License, they do not | |||||
excuse you from the conditions of this License. If you cannot convey a | |||||
covered work so as to satisfy simultaneously your obligations under this | |||||
License and any other pertinent obligations, then as a consequence you may | |||||
not convey it at all. For example, if you agree to terms that obligate you | |||||
to collect a royalty for further conveying from those to whom you convey | |||||
the Program, the only way you could satisfy both those terms and this | |||||
License would be to refrain entirely from conveying the Program. | |||||
13. Use with the GNU Affero General Public License. | |||||
Notwithstanding any other provision of this License, you have | |||||
permission to link or combine any covered work with a work licensed | |||||
under version 3 of the GNU Affero General Public License into a single | |||||
combined work, and to convey the resulting work. The terms of this | |||||
License will continue to apply to the part which is the covered work, | |||||
but the special requirements of the GNU Affero General Public License, | |||||
section 13, concerning interaction through a network will apply to the | |||||
combination as such. | |||||
14. Revised Versions of this License. | |||||
The Free Software Foundation may publish revised and/or new versions of | |||||
the GNU General Public License from time to time. Such new versions will | |||||
be similar in spirit to the present version, but may differ in detail to | |||||
address new problems or concerns. | |||||
Each version is given a distinguishing version number. If the | |||||
Program specifies that a certain numbered version of the GNU General | |||||
Public License "or any later version" applies to it, you have the | |||||
option of following the terms and conditions either of that numbered | |||||
version or of any later version published by the Free Software | |||||
Foundation. If the Program does not specify a version number of the | |||||
GNU General Public License, you may choose any version ever published | |||||
by the Free Software Foundation. | |||||
If the Program specifies that a proxy can decide which future | |||||
versions of the GNU General Public License can be used, that proxy's | |||||
public statement of acceptance of a version permanently authorizes you | |||||
to choose that version for the Program. | |||||
Later license versions may give you additional or different | |||||
permissions. However, no additional obligations are imposed on any | |||||
author or copyright holder as a result of your choosing to follow a | |||||
later version. | |||||
15. Disclaimer of Warranty. | |||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | |||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | |||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | |||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | |||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | |||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | |||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | |||||
16. Limitation of Liability. | |||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | |||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | |||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | |||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | |||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | |||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | |||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | |||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | |||||
SUCH DAMAGES. | |||||
17. Interpretation of Sections 15 and 16. | |||||
If the disclaimer of warranty and limitation of liability provided | |||||
above cannot be given local legal effect according to their terms, | |||||
reviewing courts shall apply local law that most closely approximates | |||||
an absolute waiver of all civil liability in connection with the | |||||
Program, unless a warranty or assumption of liability accompanies a | |||||
copy of the Program in return for a fee. | |||||
END OF TERMS AND CONDITIONS | |||||
How to Apply These Terms to Your New Programs | |||||
If you develop a new program, and you want it to be of the greatest | |||||
possible use to the public, the best way to achieve this is to make it | |||||
free software which everyone can redistribute and change under these terms. | |||||
To do so, attach the following notices to the program. It is safest | |||||
to attach them to the start of each source file to most effectively | |||||
state the exclusion of warranty; and each file should have at least | |||||
the "copyright" line and a pointer to where the full notice is found. | |||||
{one line to give the program's name and a brief idea of what it does.} | |||||
Copyright (C) {year} {name of author} | |||||
This program is free software: you can redistribute it and/or modify | |||||
it under the terms of the GNU General Public License as published by | |||||
the Free Software Foundation, either version 3 of the License, or | |||||
(at your option) any later version. | |||||
This program is distributed in the hope that it will be useful, | |||||
but WITHOUT ANY WARRANTY; without even the implied warranty of | |||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |||||
GNU General Public License for more details. | |||||
You should have received a copy of the GNU General Public License | |||||
along with this program. If not, see <http://www.gnu.org/licenses/>. | |||||
Also add information on how to contact you by electronic and paper mail. | |||||
If the program does terminal interaction, make it output a short | |||||
notice like this when it starts in an interactive mode: | |||||
{project} Copyright (C) {year} {fullname} | |||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. | |||||
This is free software, and you are welcome to redistribute it | |||||
under certain conditions; type `show c' for details. | |||||
The hypothetical commands `show w' and `show c' should show the appropriate | |||||
parts of the General Public License. Of course, your program's commands | |||||
might be different; for a GUI interface, you would use an "about box". | |||||
You should also get your employer (if you work as a programmer) or school, | |||||
if any, to sign a "copyright disclaimer" for the program, if necessary. | |||||
For more information on this, and how to apply and follow the GNU GPL, see | |||||
<http://www.gnu.org/licenses/>. | |||||
The GNU General Public License does not permit incorporating your program | |||||
into proprietary programs. If your program is a subroutine library, you | |||||
may consider it more useful to permit linking proprietary applications with | |||||
the library. If this is what you want to do, use the GNU Lesser General | |||||
Public License instead of this License. But first, please read | |||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>. |
@ -0,0 +1,58 @@ | |||||
sigma.neo4j.cypher | |||||
==================== | |||||
Plugin developed by [Benoît Simard](https://github.com/sim51). | |||||
--- | |||||
This plugin provides a simple function, `sigma.neo4j.cypher()`, that will run a cypher query on a neo4j instance, parse the response, eventually instantiate sigma and fill the graph with the `graph.read()` method. | |||||
Nodes are created with the following structure : | |||||
* id -> Neo4j node id | |||||
* label -> Neo4j node id | |||||
* neo4j_labels -> Labels of Neo4j node | |||||
* neo4j_data -> All the properties of the neo4j node | |||||
Edges are created with the following structure : | |||||
* id -> Neo4j edge id | |||||
* label -> Neo4j edge type | |||||
* neo4j_type -> Neo4j edge type | |||||
* neo4j_data -> All the properties of Neo4j relationship | |||||
The most basic way to use this helper is to call it with a neo4j server url and a cypher query. It will then instantiate sigma, but after having added the graph into the config object. | |||||
For neo4j < 2.2 | |||||
````javascript | |||||
sigma.neo4j.cypher( | |||||
'http://localhost:7474', | |||||
'MATCH (n) OPTIONAL MATCH (n)-[r]->(m) RETURN n,r,m LIMIT 100', | |||||
{ container: 'myContainer' } | |||||
); | |||||
```` | |||||
For neo4j >= 2.2, you must pass a neo4j user with its password. So instead of the neo4j url, you have to pass a neo4j server object like this : | |||||
````javascript | |||||
sigma.neo4j.cypher( | |||||
{ url: 'http://localhost:7474', user:'neo4j', password:'admin' }, | |||||
'MATCH (n) OPTIONAL MATCH (n)-[r]->(m) RETURN n,r,m LIMIT 100', | |||||
{ container: 'myContainer' } | |||||
); | |||||
```` | |||||
It is also possible to update an existing instance's graph instead. | |||||
````javascript | |||||
sigma.neo4j.cypher( | |||||
{ url: 'http://localhost:7474', user:'neo4j', password:'admin' }, | |||||
'MATCH (n) OPTIONAL MATCH (n)-[r]->(m) RETURN n,r,m LIMIT 100', | |||||
myExistingInstance, | |||||
function() { | |||||
myExistingInstance.refresh(); | |||||
} | |||||
); | |||||
```` | |||||
There is two additional functions provided by the plugin : | |||||
* ```sigma.neo4j.getTypes({ url: 'http://localhost:7474', user:'neo4j', password:'admin' }, callback)``` : Return all relationship type of the database | |||||
* ```sigma.neo4j.getLabels({ url: 'http://localhost:7474', user:'neo4j', password:'admin' }, callback)``` : Return all node label of the database |
@ -0,0 +1,218 @@ | |||||
;(function (undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Declare neo4j package | |||||
sigma.utils.pkg("sigma.neo4j"); | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.utils'); | |||||
/** | |||||
* This function is an helper for the neo4j communication. | |||||
* | |||||
* @param {string|object} neo4j The URL of neo4j server or a neo4j server object. | |||||
* @param {string} endpoint Endpoint of the neo4j server | |||||
* @param {string} method The calling method for the endpoint : 'GET' or 'POST' | |||||
* @param {object|string} data Data that will be send to the server | |||||
* @param {function} callback The callback function | |||||
*/ | |||||
sigma.neo4j.send = function(neo4j, endpoint, method, data, callback) { | |||||
var xhr = sigma.utils.xhr(), | |||||
url, user, password; | |||||
// if neo4j arg is not an object | |||||
url = neo4j; | |||||
if(typeof neo4j === 'object') { | |||||
url = neo4j.url; | |||||
user = neo4j.user; | |||||
password = neo4j.password; | |||||
} | |||||
if (!xhr) | |||||
throw 'XMLHttpRequest not supported, cannot load the file.'; | |||||
// Construct the endpoint url | |||||
url += endpoint; | |||||
xhr.open(method, url, true); | |||||
if( user && password) { | |||||
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(user + ':' + password)); | |||||
} | |||||
xhr.setRequestHeader('Accept', 'application/json'); | |||||
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8'); | |||||
xhr.onreadystatechange = function () { | |||||
if (xhr.readyState === 4) { | |||||
// Call the callback if specified: | |||||
callback(JSON.parse(xhr.responseText)); | |||||
} | |||||
}; | |||||
xhr.send(data); | |||||
}; | |||||
/** | |||||
* This function parse a neo4j cypher query result, and transform it into | |||||
* a sigma graph object. | |||||
* | |||||
* @param {object} result The server response of a cypher query. | |||||
* | |||||
* @return A graph object | |||||
*/ | |||||
sigma.neo4j.cypher_parse = function(result) { | |||||
var graph = { nodes: [], edges: [] }, | |||||
nodesMap = {}, | |||||
edgesMap = {}, | |||||
key; | |||||
// Iteration on all result data | |||||
result.results[0].data.forEach(function (data) { | |||||
// iteration on graph for all node | |||||
data.graph.nodes.forEach(function (node) { | |||||
var sigmaNode = { | |||||
id : node.id, | |||||
label : node.id, | |||||
x : Math.random(), | |||||
y : Math.random(), | |||||
size : 1, | |||||
color : '#000000', | |||||
neo4j_labels : node.labels, | |||||
neo4j_data : node.properties | |||||
}; | |||||
if (sigmaNode.id in nodesMap) { | |||||
// do nothing | |||||
} else { | |||||
nodesMap[sigmaNode.id] = sigmaNode; | |||||
} | |||||
}); | |||||
// iteration on graph for all node | |||||
data.graph.relationships.forEach(function (edge) { | |||||
var sigmaEdge = { | |||||
id : edge.id, | |||||
label : edge.type, | |||||
source : edge.startNode, | |||||
target : edge.endNode, | |||||
color : '#7D7C8E', | |||||
neo4j_type : edge.type, | |||||
neo4j_data : edge.properties | |||||
}; | |||||
if (sigmaEdge.id in edgesMap) { | |||||
// do nothing | |||||
} else { | |||||
edgesMap[sigmaEdge.id] = sigmaEdge; | |||||
} | |||||
}); | |||||
}); | |||||
// construct sigma nodes | |||||
for (key in nodesMap) { | |||||
graph.nodes.push(nodesMap[key]); | |||||
} | |||||
// construct sigma nodes | |||||
for (key in edgesMap) { | |||||
graph.edges.push(edgesMap[key]); | |||||
} | |||||
return graph; | |||||
}; | |||||
/** | |||||
* This function execute a cypher and create a new sigma instance or | |||||
* updates the graph of a given instance. It is possible to give a callback | |||||
* that will be executed at the end of the process. | |||||
* | |||||
* @param {object|string} neo4j The URL of neo4j server or a neo4j server object. | |||||
* @param {string} cypher The cypher query | |||||
* @param {?object|?sigma} sig A sigma configuration object or a sigma instance. | |||||
* @param {?function} callback Eventually a callback to execute after | |||||
* having parsed the file. It will be called | |||||
* with the related sigma instance as | |||||
* parameter. | |||||
*/ | |||||
sigma.neo4j.cypher = function (neo4j, cypher, sig, callback) { | |||||
var endpoint = '/db/data/transaction/commit', | |||||
data, cypherCallback; | |||||
// Data that will be send to the server | |||||
data = JSON.stringify({ | |||||
"statements": [ | |||||
{ | |||||
"statement": cypher, | |||||
"resultDataContents": ["graph"], | |||||
"includeStats": false | |||||
} | |||||
] | |||||
}); | |||||
// Callback method after server response | |||||
cypherCallback = function (callback) { | |||||
return function (response) { | |||||
var graph = { nodes: [], edges: [] }; | |||||
graph = sigma.neo4j.cypher_parse(response); | |||||
// Update the instance's graph: | |||||
if (sig instanceof sigma) { | |||||
sig.graph.clear(); | |||||
sig.graph.read(graph); | |||||
// ...or instantiate sigma if needed: | |||||
} else if (typeof sig === 'object') { | |||||
sig = new sigma(sig); | |||||
sig.graph.read(graph); | |||||
sig.refresh(); | |||||
// ...or it's finally the callback: | |||||
} else if (typeof sig === 'function') { | |||||
callback = sig; | |||||
sig = null; | |||||
} | |||||
// Call the callback if specified: | |||||
if (callback) | |||||
callback(sig || graph); | |||||
}; | |||||
}; | |||||
// Let's call neo4j | |||||
sigma.neo4j.send(neo4j, endpoint, 'POST', data, cypherCallback(callback)); | |||||
}; | |||||
/** | |||||
* This function call neo4j to get all labels of the graph. | |||||
* | |||||
* @param {string} neo4j The URL of neo4j server or an object with the url, user & password. | |||||
* @param {function} callback The callback function | |||||
* | |||||
* @return An array of label | |||||
*/ | |||||
sigma.neo4j.getLabels = function(neo4j, callback) { | |||||
sigma.neo4j.send(neo4j, '/db/data/labels', 'GET', null, callback); | |||||
}; | |||||
/** | |||||
* This function parse a neo4j cypher query result. | |||||
* | |||||
* @param {string} neo4j The URL of neo4j server or an object with the url, user & password. | |||||
* @param {function} callback The callback function | |||||
* | |||||
* @return An array of relationship type | |||||
*/ | |||||
sigma.neo4j.getTypes = function(neo4j, callback) { | |||||
sigma.neo4j.send(neo4j, '/db/data/relationship/types', 'GET', null, callback); | |||||
}; | |||||
}).call(this); | |||||
@ -0,0 +1,29 @@ | |||||
sigma.parsers.gexf | |||||
================== | |||||
Plugin developed by [Alexis Jacomy](https://github.com/jacomyal), on top of [gexf-parser](https://github.com/Yomguithereal/gexf-parser), developed by [Guillaume Plique](https://github.com/Yomguithereal). | |||||
--- | |||||
This plugin provides a single function, `sigma.parsers.gexf()`, that will load a GEXF encoded file, parse it, and instantiate sigma. | |||||
The most basic way to use this helper is to call it with a path and a sigma configuration object. It will then instantiate sigma, but after having added the graph into the config object. | |||||
````javascript | |||||
sigma.parsers.gexf( | |||||
'myGraph.gexf', | |||||
{ container: 'myContainer' } | |||||
); | |||||
```` | |||||
It is also possible to update an existing instance's graph instead. | |||||
````javascript | |||||
sigma.parsers.gexf( | |||||
'myGraph.gexf', | |||||
myExistingInstance, | |||||
function() { | |||||
myExistingInstance.refresh(); | |||||
} | |||||
); | |||||
```` |
@ -0,0 +1,551 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
/** | |||||
* GEXF Library | |||||
* ============= | |||||
* | |||||
* Author: PLIQUE Guillaume (Yomguithereal) | |||||
* URL: https://github.com/Yomguithereal/gexf-parser | |||||
* Version: 0.1.1 | |||||
*/ | |||||
/** | |||||
* Helper Namespace | |||||
* ----------------- | |||||
* | |||||
* A useful batch of function dealing with DOM operations and types. | |||||
*/ | |||||
var _helpers = { | |||||
getModelTags: function(xml) { | |||||
var attributesTags = xml.getElementsByTagName('attributes'), | |||||
modelTags = {}, | |||||
l = attributesTags.length, | |||||
i; | |||||
for (i = 0; i < l; i++) | |||||
modelTags[attributesTags[i].getAttribute('class')] = | |||||
attributesTags[i].childNodes; | |||||
return modelTags; | |||||
}, | |||||
nodeListToArray: function(nodeList) { | |||||
// Return array | |||||
var children = []; | |||||
// Iterating | |||||
for (var i = 0, len = nodeList.length; i < len; ++i) { | |||||
if (nodeList[i].nodeName !== '#text') | |||||
children.push(nodeList[i]); | |||||
} | |||||
return children; | |||||
}, | |||||
nodeListEach: function(nodeList, func) { | |||||
// Iterating | |||||
for (var i = 0, len = nodeList.length; i < len; ++i) { | |||||
if (nodeList[i].nodeName !== '#text') | |||||
func(nodeList[i]); | |||||
} | |||||
}, | |||||
nodeListToHash: function(nodeList, filter) { | |||||
// Return object | |||||
var children = {}; | |||||
// Iterating | |||||
for (var i = 0; i < nodeList.length; i++) { | |||||
if (nodeList[i].nodeName !== '#text') { | |||||
var prop = filter(nodeList[i]); | |||||
children[prop.key] = prop.value; | |||||
} | |||||
} | |||||
return children; | |||||
}, | |||||
namedNodeMapToObject: function(nodeMap) { | |||||
// Return object | |||||
var attributes = {}; | |||||
// Iterating | |||||
for (var i = 0; i < nodeMap.length; i++) { | |||||
attributes[nodeMap[i].name] = nodeMap[i].value; | |||||
} | |||||
return attributes; | |||||
}, | |||||
getFirstElementByTagNS: function(node, ns, tag) { | |||||
var el = node.getElementsByTagName(ns + ':' + tag)[0]; | |||||
if (!el) | |||||
el = node.getElementsByTagNameNS(ns, tag)[0]; | |||||
if (!el) | |||||
el = node.getElementsByTagName(tag)[0]; | |||||
return el; | |||||
}, | |||||
getAttributeNS: function(node, ns, attribute) { | |||||
var attr_value = node.getAttribute(ns + ':' + attribute); | |||||
if (attr_value === undefined) | |||||
attr_value = node.getAttributeNS(ns, attribute); | |||||
if (attr_value === undefined) | |||||
attr_value = node.getAttribute(attribute); | |||||
return attr_value; | |||||
}, | |||||
enforceType: function(type, value) { | |||||
switch (type) { | |||||
case 'boolean': | |||||
value = (value === 'true'); | |||||
break; | |||||
case 'integer': | |||||
case 'long': | |||||
case 'float': | |||||
case 'double': | |||||
value = +value; | |||||
break; | |||||
case 'liststring': | |||||
value = value ? value.split('|') : []; | |||||
break; | |||||
} | |||||
return value; | |||||
}, | |||||
getRGB: function(values) { | |||||
return (values[3]) ? | |||||
'rgba(' + values.join(',') + ')' : | |||||
'rgb(' + values.slice(0, -1).join(',') + ')'; | |||||
} | |||||
}; | |||||
/** | |||||
* Parser Core Functions | |||||
* ---------------------- | |||||
* | |||||
* The XML parser's functions themselves. | |||||
*/ | |||||
/** | |||||
* Node structure. | |||||
* A function returning an object guarded with default value. | |||||
* | |||||
* @param {object} properties The node properties. | |||||
* @return {object} The guarded node object. | |||||
*/ | |||||
function Node(properties) { | |||||
// Possible Properties | |||||
var node = { | |||||
id: properties.id, | |||||
label: properties.label | |||||
}; | |||||
if (properties.viz) | |||||
node.viz = properties.viz; | |||||
if (properties.attributes) | |||||
node.attributes = properties.attributes; | |||||
return node; | |||||
} | |||||
/** | |||||
* Edge structure. | |||||
* A function returning an object guarded with default value. | |||||
* | |||||
* @param {object} properties The edge properties. | |||||
* @return {object} The guarded edge object. | |||||
*/ | |||||
function Edge(properties) { | |||||
// Possible Properties | |||||
var edge = { | |||||
id: properties.id, | |||||
type: properties.type || 'undirected', | |||||
label: properties.label || '', | |||||
source: properties.source, | |||||
target: properties.target, | |||||
weight: +properties.weight || 1.0 | |||||
}; | |||||
if (properties.viz) | |||||
edge.viz = properties.viz; | |||||
if (properties.attributes) | |||||
edge.attributes = properties.attributes; | |||||
return edge; | |||||
} | |||||
/** | |||||
* Graph parser. | |||||
* This structure parse a gexf string and return an object containing the | |||||
* parsed graph. | |||||
* | |||||
* @param {string} xml The xml string of the gexf file to parse. | |||||
* @return {object} The parsed graph. | |||||
*/ | |||||
function Graph(xml) { | |||||
var _xml = {}; | |||||
// Basic Properties | |||||
//------------------ | |||||
_xml.els = { | |||||
root: xml.getElementsByTagName('gexf')[0], | |||||
graph: xml.getElementsByTagName('graph')[0], | |||||
meta: xml.getElementsByTagName('meta')[0], | |||||
nodes: xml.getElementsByTagName('node'), | |||||
edges: xml.getElementsByTagName('edge'), | |||||
model: _helpers.getModelTags(xml) | |||||
}; | |||||
// Information | |||||
_xml.hasViz = !!_helpers.getAttributeNS(_xml.els.root, 'xmlns', 'viz'); | |||||
_xml.version = _xml.els.root.getAttribute('version') || '1.0'; | |||||
_xml.mode = _xml.els.graph.getAttribute('mode') || 'static'; | |||||
var edgeType = _xml.els.graph.getAttribute('defaultedgetype'); | |||||
_xml.defaultEdgetype = edgeType || 'undirected'; | |||||
// Parser Functions | |||||
//------------------ | |||||
// Meta Data | |||||
function _metaData() { | |||||
var metas = {}; | |||||
if (!_xml.els.meta) | |||||
return metas; | |||||
// Last modified date | |||||
metas.lastmodifieddate = _xml.els.meta.getAttribute('lastmodifieddate'); | |||||
// Other information | |||||
_helpers.nodeListEach(_xml.els.meta.childNodes, function(child) { | |||||
metas[child.tagName.toLowerCase()] = child.textContent; | |||||
}); | |||||
return metas; | |||||
} | |||||
// Model | |||||
function _model(cls) { | |||||
var attributes = []; | |||||
// Iterating through attributes | |||||
if (_xml.els.model[cls]) | |||||
_helpers.nodeListEach(_xml.els.model[cls], function(attr) { | |||||
// Properties | |||||
var properties = { | |||||
id: attr.getAttribute('id') || attr.getAttribute('for'), | |||||
type: attr.getAttribute('type') || 'string', | |||||
title: attr.getAttribute('title') || '' | |||||
}; | |||||
// Defaults | |||||
var default_el = _helpers.nodeListToArray(attr.childNodes); | |||||
if (default_el.length > 0) | |||||
properties.defaultValue = default_el[0].textContent; | |||||
// Creating attribute | |||||
attributes.push(properties); | |||||
}); | |||||
return attributes.length > 0 ? attributes : false; | |||||
} | |||||
// Data from nodes or edges | |||||
function _data(model, node_or_edge) { | |||||
var data = {}; | |||||
var attvalues_els = node_or_edge.getElementsByTagName('attvalue'); | |||||
// Getting Node Indicated Attributes | |||||
var ah = _helpers.nodeListToHash(attvalues_els, function(el) { | |||||
var attributes = _helpers.namedNodeMapToObject(el.attributes); | |||||
var key = attributes.id || attributes['for']; | |||||
// Returning object | |||||
return {key: key, value: attributes.value}; | |||||
}); | |||||
// Iterating through model | |||||
model.map(function(a) { | |||||
// Default value? | |||||
data[a.id] = !(a.id in ah) && 'defaultValue' in a ? | |||||
_helpers.enforceType(a.type, a.defaultValue) : | |||||
_helpers.enforceType(a.type, ah[a.id]); | |||||
}); | |||||
return data; | |||||
} | |||||
// Nodes | |||||
function _nodes(model) { | |||||
var nodes = []; | |||||
// Iteration through nodes | |||||
_helpers.nodeListEach(_xml.els.nodes, function(n) { | |||||
// Basic properties | |||||
var properties = { | |||||
id: n.getAttribute('id'), | |||||
label: n.getAttribute('label') || '' | |||||
}; | |||||
// Retrieving data from nodes if any | |||||
if (model) | |||||
properties.attributes = _data(model, n); | |||||
// Retrieving viz information | |||||
if (_xml.hasViz) | |||||
properties.viz = _nodeViz(n); | |||||
// Pushing node | |||||
nodes.push(Node(properties)); | |||||
}); | |||||
return nodes; | |||||
} | |||||
// Viz information from nodes | |||||
function _nodeViz(node) { | |||||
var viz = {}; | |||||
// Color | |||||
var color_el = _helpers.getFirstElementByTagNS(node, 'viz', 'color'); | |||||
if (color_el) { | |||||
var color = ['r', 'g', 'b', 'a'].map(function(c) { | |||||
return color_el.getAttribute(c); | |||||
}); | |||||
viz.color = _helpers.getRGB(color); | |||||
} | |||||
// Position | |||||
var pos_el = _helpers.getFirstElementByTagNS(node, 'viz', 'position'); | |||||
if (pos_el) { | |||||
viz.position = {}; | |||||
['x', 'y', 'z'].map(function(p) { | |||||
viz.position[p] = +pos_el.getAttribute(p); | |||||
}); | |||||
} | |||||
// Size | |||||
var size_el = _helpers.getFirstElementByTagNS(node, 'viz', 'size'); | |||||
if (size_el) | |||||
viz.size = +size_el.getAttribute('value'); | |||||
// Shape | |||||
var shape_el = _helpers.getFirstElementByTagNS(node, 'viz', 'shape'); | |||||
if (shape_el) | |||||
viz.shape = shape_el.getAttribute('value'); | |||||
return viz; | |||||
} | |||||
// Edges | |||||
function _edges(model, default_type) { | |||||
var edges = []; | |||||
// Iteration through edges | |||||
_helpers.nodeListEach(_xml.els.edges, function(e) { | |||||
// Creating the edge | |||||
var properties = _helpers.namedNodeMapToObject(e.attributes); | |||||
if (!('type' in properties)) { | |||||
properties.type = default_type; | |||||
} | |||||
// Retrieving edge data | |||||
if (model) | |||||
properties.attributes = _data(model, e); | |||||
// Retrieving viz information | |||||
if (_xml.hasViz) | |||||
properties.viz = _edgeViz(e); | |||||
edges.push(Edge(properties)); | |||||
}); | |||||
return edges; | |||||
} | |||||
// Viz information from edges | |||||
function _edgeViz(edge) { | |||||
var viz = {}; | |||||
// Color | |||||
var color_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'color'); | |||||
if (color_el) { | |||||
var color = ['r', 'g', 'b', 'a'].map(function(c) { | |||||
return color_el.getAttribute(c); | |||||
}); | |||||
viz.color = _helpers.getRGB(color); | |||||
} | |||||
// Shape | |||||
var shape_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'shape'); | |||||
if (shape_el) | |||||
viz.shape = shape_el.getAttribute('value'); | |||||
// Thickness | |||||
var thick_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'thickness'); | |||||
if (thick_el) | |||||
viz.thickness = +thick_el.getAttribute('value'); | |||||
return viz; | |||||
} | |||||
// Returning the Graph | |||||
//--------------------- | |||||
var nodeModel = _model('node'), | |||||
edgeModel = _model('edge'); | |||||
var graph = { | |||||
version: _xml.version, | |||||
mode: _xml.mode, | |||||
defaultEdgeType: _xml.defaultEdgetype, | |||||
meta: _metaData(), | |||||
model: {}, | |||||
nodes: _nodes(nodeModel), | |||||
edges: _edges(edgeModel, _xml.defaultEdgetype) | |||||
}; | |||||
if (nodeModel) | |||||
graph.model.node = nodeModel; | |||||
if (edgeModel) | |||||
graph.model.edge = edgeModel; | |||||
return graph; | |||||
} | |||||
/** | |||||
* Public API | |||||
* ----------- | |||||
* | |||||
* User-accessible functions. | |||||
*/ | |||||
// Fetching GEXF with XHR | |||||
function fetch(gexf_url, callback) { | |||||
var xhr = (function() { | |||||
if (window.XMLHttpRequest) | |||||
return new XMLHttpRequest(); | |||||
var names, | |||||
i; | |||||
if (window.ActiveXObject) { | |||||
names = [ | |||||
'Msxml2.XMLHTTP.6.0', | |||||
'Msxml2.XMLHTTP.3.0', | |||||
'Msxml2.XMLHTTP', | |||||
'Microsoft.XMLHTTP' | |||||
]; | |||||
for (i in names) | |||||
try { | |||||
return new ActiveXObject(names[i]); | |||||
} catch (e) {} | |||||
} | |||||
return null; | |||||
})(); | |||||
if (!xhr) | |||||
throw 'XMLHttpRequest not supported, cannot load the file.'; | |||||
// Async? | |||||
var async = (typeof callback === 'function'), | |||||
getResult; | |||||
// If we can't override MIME type, we are on IE 9 | |||||
// We'll be parsing the response string then. | |||||
if (xhr.overrideMimeType) { | |||||
xhr.overrideMimeType('text/xml'); | |||||
getResult = function(r) { | |||||
return r.responseXML; | |||||
}; | |||||
} | |||||
else { | |||||
getResult = function(r) { | |||||
var p = new DOMParser(); | |||||
return p.parseFromString(r.responseText, 'application/xml'); | |||||
}; | |||||
} | |||||
xhr.open('GET', gexf_url, async); | |||||
if (async) | |||||
xhr.onreadystatechange = function() { | |||||
if (xhr.readyState === 4) | |||||
callback(getResult(xhr)); | |||||
}; | |||||
xhr.send(); | |||||
return (async) ? xhr : getResult(xhr); | |||||
} | |||||
// Parsing the GEXF File | |||||
function parse(gexf) { | |||||
return Graph(gexf); | |||||
} | |||||
// Fetch and parse the GEXF File | |||||
function fetchAndParse(gexf_url, callback) { | |||||
if (typeof callback === 'function') { | |||||
return fetch(gexf_url, function(gexf) { | |||||
callback(Graph(gexf)); | |||||
}); | |||||
} else | |||||
return Graph(fetch(gexf_url)); | |||||
} | |||||
/** | |||||
* Exporting | |||||
* ---------- | |||||
*/ | |||||
if (typeof this.gexf !== 'undefined') | |||||
throw 'gexf: error - a variable called "gexf" already ' + | |||||
'exists in the global scope'; | |||||
this.gexf = { | |||||
// Functions | |||||
parse: parse, | |||||
fetch: fetchAndParse, | |||||
// Version | |||||
version: '0.1.1' | |||||
}; | |||||
if (typeof exports !== 'undefined' && this.exports !== exports) | |||||
module.exports = this.gexf; | |||||
}).call(this); |
@ -0,0 +1,112 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.parsers'); | |||||
// Just a basic ID generator: | |||||
var _id = 0; | |||||
function edgeId() { | |||||
return 'e' + (_id++); | |||||
} | |||||
/** | |||||
* If the first arguments is a valid URL, this function loads a GEXF file and | |||||
* creates a new sigma instance or updates the graph of a given instance. It | |||||
* is possible to give a callback that will be executed at the end of the | |||||
* process. And if the first argument is a DOM element, it will skip the | |||||
* loading step and parse the given XML tree to fill the graph. | |||||
* | |||||
* @param {string|DOMElement} target The URL of the GEXF file or a valid | |||||
* GEXF tree. | |||||
* @param {object|sigma} sig A sigma configuration object or a | |||||
* sigma instance. | |||||
* @param {?function} callback Eventually a callback to execute | |||||
* after having parsed the file. It will | |||||
* be called with the related sigma | |||||
* instance as parameter. | |||||
*/ | |||||
sigma.parsers.gexf = function(target, sig, callback) { | |||||
var i, | |||||
l, | |||||
arr, | |||||
obj; | |||||
function parse(graph) { | |||||
// Adapt the graph: | |||||
arr = graph.nodes; | |||||
for (i = 0, l = arr.length; i < l; i++) { | |||||
obj = arr[i]; | |||||
obj.id = obj.id; | |||||
if (obj.viz && typeof obj.viz === 'object') { | |||||
if (obj.viz.position && typeof obj.viz.position === 'object') { | |||||
obj.x = obj.viz.position.x; | |||||
obj.y = -obj.viz.position.y; // Needed otherwise it's up side down | |||||
} | |||||
obj.size = obj.viz.size; | |||||
obj.color = obj.viz.color; | |||||
} | |||||
} | |||||
arr = graph.edges; | |||||
for (i = 0, l = arr.length; i < l; i++) { | |||||
obj = arr[i]; | |||||
obj.id = typeof obj.id === 'string' ? obj.id : edgeId(); | |||||
obj.source = '' + obj.source; | |||||
obj.target = '' + obj.target; | |||||
if (obj.viz && typeof obj.viz === 'object') { | |||||
obj.color = obj.viz.color; | |||||
obj.size = obj.viz.thickness; | |||||
} | |||||
// Weight over viz.thickness? | |||||
obj.size = obj.weight; | |||||
// Changing type to be direction so it won't mess with sigma's naming | |||||
obj.direction = obj.type; | |||||
delete obj.type; | |||||
} | |||||
// Update the instance's graph: | |||||
if (sig instanceof sigma) { | |||||
sig.graph.clear(); | |||||
arr = graph.nodes; | |||||
for (i = 0, l = arr.length; i < l; i++) | |||||
sig.graph.addNode(arr[i]); | |||||
arr = graph.edges; | |||||
for (i = 0, l = arr.length; i < l; i++) | |||||
sig.graph.addEdge(arr[i]); | |||||
// ...or instantiate sigma if needed: | |||||
} else if (typeof sig === 'object') { | |||||
sig.graph = graph; | |||||
sig = new sigma(sig); | |||||
// ...or it's finally the callback: | |||||
} else if (typeof sig === 'function') { | |||||
callback = sig; | |||||
sig = null; | |||||
} | |||||
// Call the callback if specified: | |||||
if (callback) { | |||||
callback(sig || graph); | |||||
return; | |||||
} else | |||||
return graph; | |||||
} | |||||
if (typeof target === 'string') | |||||
gexf.fetch(target, parse); | |||||
else if (typeof target === 'object') | |||||
return parse(gexf.parse(target)); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,29 @@ | |||||
sigma.parsers.json | |||||
================== | |||||
Plugin developed by [Alexis Jacomy](https://github.com/jacomyal). | |||||
--- | |||||
This plugin provides a single function, `sigma.parsers.json()`, that will load a JSON encoded file, parse it, eventually instantiate sigma and fill the graph with the `graph.read()` method. The main goal is to avoid using jQuery only to load an external JSON file. | |||||
The most basic way to use this helper is to call it with a path and a sigma configuration object. It will then instanciate sigma, but after having added the graph into the config object. | |||||
````javascript | |||||
sigma.parsers.json( | |||||
'myGraph.json', | |||||
{ container: 'myContainer' } | |||||
); | |||||
```` | |||||
It is also possible to update an existing instance's graph instead. | |||||
````javascript | |||||
sigma.parsers.json( | |||||
'myGraph.json', | |||||
myExistingInstance, | |||||
function() { | |||||
myExistingInstance.refresh(); | |||||
} | |||||
); | |||||
```` |
@ -0,0 +1,88 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.parsers'); | |||||
sigma.utils.pkg('sigma.utils'); | |||||
/** | |||||
* Just an XmlHttpRequest polyfill for different IE versions. | |||||
* | |||||
* @return {*} The XHR like object. | |||||
*/ | |||||
sigma.utils.xhr = function() { | |||||
if (window.XMLHttpRequest) | |||||
return new XMLHttpRequest(); | |||||
var names, | |||||
i; | |||||
if (window.ActiveXObject) { | |||||
names = [ | |||||
'Msxml2.XMLHTTP.6.0', | |||||
'Msxml2.XMLHTTP.3.0', | |||||
'Msxml2.XMLHTTP', | |||||
'Microsoft.XMLHTTP' | |||||
]; | |||||
for (i in names) | |||||
try { | |||||
return new ActiveXObject(names[i]); | |||||
} catch (e) {} | |||||
} | |||||
return null; | |||||
}; | |||||
/** | |||||
* This function loads a JSON file and creates a new sigma instance or | |||||
* updates the graph of a given instance. It is possible to give a callback | |||||
* that will be executed at the end of the process. | |||||
* | |||||
* @param {string} url The URL of the JSON file. | |||||
* @param {object|sigma} sig A sigma configuration object or a sigma | |||||
* instance. | |||||
* @param {?function} callback Eventually a callback to execute after | |||||
* having parsed the file. It will be called | |||||
* with the related sigma instance as | |||||
* parameter. | |||||
*/ | |||||
sigma.parsers.json = function(url, sig, callback) { | |||||
var graph, | |||||
xhr = sigma.utils.xhr(); | |||||
if (!xhr) | |||||
throw 'XMLHttpRequest not supported, cannot load the file.'; | |||||
xhr.open('GET', url, true); | |||||
xhr.onreadystatechange = function() { | |||||
if (xhr.readyState === 4) { | |||||
graph = JSON.parse(xhr.responseText); | |||||
// Update the instance's graph: | |||||
if (sig instanceof sigma) { | |||||
sig.graph.clear(); | |||||
sig.graph.read(graph); | |||||
// ...or instantiate sigma if needed: | |||||
} else if (typeof sig === 'object') { | |||||
sig.graph = graph; | |||||
sig = new sigma(sig); | |||||
// ...or it's finally the callback: | |||||
} else if (typeof sig === 'function') { | |||||
callback = sig; | |||||
sig = null; | |||||
} | |||||
// Call the callback if specified: | |||||
if (callback) | |||||
callback(sig || graph); | |||||
} | |||||
}; | |||||
xhr.send(); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,25 @@ | |||||
This is free and unencumbered software released into the public domain. | |||||
Anyone is free to copy, modify, publish, use, compile, sell, or | |||||
distribute this software, either in source code form or as a compiled | |||||
binary, for any purpose, commercial or non-commercial, and by any | |||||
means. | |||||
In jurisdictions that recognize copyright laws, the author or authors | |||||
of this software dedicate any and all copyright interest in the | |||||
software to the public domain. We make this dedication for the benefit | |||||
of the public at large and to the detriment of our heirs and | |||||
successors. We intend this dedication to be an overt act of | |||||
relinquishment in perpetuity of all present and future rights to this | |||||
software under copyright law. | |||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |||||
OTHER DEALINGS IN THE SOFTWARE. | |||||
For more information, please refer to <http://unlicense.org> | |||||
@ -0,0 +1,27 @@ | |||||
sigma.pathfinding.astar.js — v1.0.0 | |||||
=================================== | |||||
> Plugin author: [@A----](https://github.com/A----) | |||||
> Main repository for this plugin is here: https://github.com/A----/sigma-pathfinding-astar | |||||
> Please report issues, make PR, there. | |||||
> This project is released under Public Domain license (see LICENSE for more information). | |||||
*sigma.pathfinding.astar.js* is a plugin for [sigma.js](http://sigmajs.org) that computes path in a graph | |||||
using a naive implementation of the [A*](http://en.wikipedia.org/wiki/A*_search_algorithm) algorithm. | |||||
## Usage | |||||
Either download a tarball, `git clone` the repository or `npm install` it. Then it's pretty straight-forward. | |||||
It adds a method to your `sigma.graph` called `astar(srcId, destId[, options])`. | |||||
- `srcId`, identifier of the start node; | |||||
- `destId`, identification of the destination node; | |||||
- `options` (optional), an object containing one or more of those properties: | |||||
- `undirected` (default: `false`), if set to `true`, consider the graph as non-oriented (will explore all edges, including the inbound ones); | |||||
- `pathLengthFunction` (default is the geometrical distance), a `function(node1, node2, previousLength)` that should return the new path length between the start node and `node2`, knowing that the path length between the start node and `node1` is contained in `previousLength`. | |||||
- `heuristicLengthFunction` (default: `undefined`), a `function(node1, node2)` guesses the path length between `node1` and `node2` (`node2` actually is the destination node). If left undefined, takes the `pathLengthFunction` option (third parameter will be left undefined). | |||||
Return value is either: | |||||
- `undefined`: no path could be found between the source node and the destination node; | |||||
- `[srcNode, …, destNode ]`: an array of nodes, including source and destination node. |
@ -0,0 +1,134 @@ | |||||
(function() { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') { | |||||
throw 'sigma is not declared'; | |||||
} | |||||
// Default function to compute path length between two nodes: | |||||
// the euclidian | |||||
var defaultPathLengthFunction = function(node1, node2, previousPathLength) { | |||||
var isEverythingDefined = | |||||
node1 != undefined && | |||||
node2 != undefined && | |||||
node1.x != undefined && | |||||
node1.y != undefined && | |||||
node2.x != undefined && | |||||
node2.y != undefined; | |||||
if(!isEverythingDefined) { | |||||
return undefined; | |||||
} | |||||
return (previousPathLength || 0) + Math.sqrt( | |||||
Math.pow((node2.y - node1.y), 2) + Math.pow((node2.x - node1.x), 2) | |||||
); | |||||
}; | |||||
sigma.classes.graph.addMethod( | |||||
'astar', | |||||
function(srcId, destId, settings) { | |||||
var currentSettings = new sigma.classes.configurable( | |||||
// Default settings | |||||
{ | |||||
// Graph is directed, affects which edges are taken into account | |||||
undirected: false, | |||||
// Function to compute the distance between two connected node | |||||
pathLengthFunction: defaultPathLengthFunction, | |||||
// Function to compute an distance between two nodes | |||||
// if undefined, uses pathLengthFunction | |||||
heuristicLengthFunction: undefined | |||||
}, | |||||
settings || {}); | |||||
var pathLengthFunction = currentSettings("pathLengthFunction"), | |||||
heuristicLengthFunction = currentSettings("heuristicLengthFunction") || pathLengthFunction; | |||||
var srcNode = this.nodes(srcId), | |||||
destNode = this.nodes(destId); | |||||
var closedList = {}, | |||||
openList = []; | |||||
var addToLists = function(node, previousNode, pathLength, heuristicLength) { | |||||
var nodeId = node.id; | |||||
var newItem = { | |||||
pathLength: pathLength, | |||||
heuristicLength: heuristicLength, | |||||
node: node, | |||||
nodeId: nodeId, | |||||
previousNode: previousNode | |||||
}; | |||||
if(closedList[nodeId] == undefined || closedList[nodeId].pathLength > pathLength) { | |||||
closedList[nodeId] = newItem; | |||||
var item; | |||||
var i; | |||||
for(i = 0; i < openList.length; i++) { | |||||
item = openList[i]; | |||||
if(item.heuristicLength > heuristicLength) { | |||||
break; | |||||
} | |||||
} | |||||
openList.splice(i, 0, newItem); | |||||
} | |||||
}; | |||||
addToLists(srcNode, null, 0, 0); | |||||
var pathFound = false; | |||||
// Depending of the type of graph (directed or not), | |||||
// the neighbors are either the out neighbors or all. | |||||
var allNeighbors; | |||||
if(currentSettings("undirected")) { | |||||
allNeighbors = this.allNeighborsIndex; | |||||
} | |||||
else { | |||||
allNeighbors = this.outNeighborsIndex; | |||||
} | |||||
var inspectedItem, | |||||
neighbors, | |||||
neighbor, | |||||
pathLength, | |||||
heuristicLength, | |||||
i; | |||||
while(openList.length > 0) { | |||||
inspectedItem = openList.shift(); | |||||
// We reached the destination node | |||||
if(inspectedItem.nodeId == destId) { | |||||
pathFound = true; | |||||
break; | |||||
} | |||||
neighbors = Object.keys(allNeighbors[inspectedItem.nodeId]); | |||||
for(i = 0; i < neighbors.length; i++) { | |||||
neighbor = this.nodes(neighbors[i]); | |||||
pathLength = pathLengthFunction(inspectedItem.node, neighbor, inspectedItem.pathLength); | |||||
heuristicLength = heuristicLengthFunction(neighbor, destNode); | |||||
addToLists(neighbor, inspectedItem.node, pathLength, heuristicLength); | |||||
} | |||||
} | |||||
if(pathFound) { | |||||
// Rebuilding path | |||||
var path = [], | |||||
currentNode = destNode; | |||||
while(currentNode) { | |||||
path.unshift(currentNode); | |||||
currentNode = closedList[currentNode.id].previousNode; | |||||
} | |||||
return path; | |||||
} | |||||
else { | |||||
return undefined; | |||||
} | |||||
} | |||||
); | |||||
}).call(window); |
@ -0,0 +1,71 @@ | |||||
sigma.plugins.animate | |||||
===================== | |||||
Plugin developed by [Alexis Jacomy](https://github.com/jacomyal). | |||||
--- | |||||
This plugin provides a method to animate a sigma instance by interpolating some node properties. Check the `sigma.plugins.animate` function doc or the `examples/animate.html` code sample to know more. | |||||
Interpolate coordinates as follows: | |||||
```js | |||||
sigma.plugins.animate( | |||||
s, | |||||
{ | |||||
x: 'target_x', | |||||
y: 'target_y', | |||||
} | |||||
); | |||||
``` | |||||
Interpolate colors and sizes as follows: | |||||
```js | |||||
sigma.plugins.animate( | |||||
s, | |||||
{ | |||||
size: 'target_size', | |||||
color: 'target_color' | |||||
} | |||||
); | |||||
``` | |||||
Animate a subset of nodes as follows: | |||||
```js | |||||
sigma.plugins.animate( | |||||
s, | |||||
{ | |||||
x: 'to_x', | |||||
y: 'to_y', | |||||
size: 'to_size', | |||||
color: 'to_color' | |||||
}, | |||||
{ | |||||
nodes: ['n0', 'n1', 'n2'] | |||||
} | |||||
); | |||||
``` | |||||
Example using all options: | |||||
```js | |||||
sigma.plugins.animate( | |||||
s, | |||||
{ | |||||
x: 'to_x', | |||||
y: 'to_y', | |||||
size: 'to_size', | |||||
color: 'to_color' | |||||
}, | |||||
{ | |||||
nodes: ['n0', 'n1', 'n2'], | |||||
easing: 'cubicInOut', | |||||
duration: 300, | |||||
onComplete: function() { | |||||
// do stuff here after animation is complete | |||||
} | |||||
} | |||||
); | |||||
``` |
@ -0,0 +1,204 @@ | |||||
/** | |||||
* This plugin provides a method to animate a sigma instance by interpolating | |||||
* some node properties. Check the sigma.plugins.animate function doc or the | |||||
* examples/animate.html code sample to know more. | |||||
*/ | |||||
(function() { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
sigma.utils.pkg('sigma.plugins'); | |||||
var _id = 0, | |||||
_cache = {}; | |||||
// TOOLING FUNCTIONS: | |||||
// ****************** | |||||
function parseColor(val) { | |||||
if (_cache[val]) | |||||
return _cache[val]; | |||||
var result = [0, 0, 0]; | |||||
if (val.match(/^#/)) { | |||||
val = (val || '').replace(/^#/, ''); | |||||
result = (val.length === 3) ? | |||||
[ | |||||
parseInt(val.charAt(0) + val.charAt(0), 16), | |||||
parseInt(val.charAt(1) + val.charAt(1), 16), | |||||
parseInt(val.charAt(2) + val.charAt(2), 16) | |||||
] : | |||||
[ | |||||
parseInt(val.charAt(0) + val.charAt(1), 16), | |||||
parseInt(val.charAt(2) + val.charAt(3), 16), | |||||
parseInt(val.charAt(4) + val.charAt(5), 16) | |||||
]; | |||||
} else if (val.match(/^ *rgba? *\(/)) { | |||||
val = val.match( | |||||
/^ *rgba? *\( *([0-9]*) *, *([0-9]*) *, *([0-9]*) *(,.*)?\) *$/ | |||||
); | |||||
result = [ | |||||
+val[1], | |||||
+val[2], | |||||
+val[3] | |||||
]; | |||||
} | |||||
_cache[val] = { | |||||
r: result[0], | |||||
g: result[1], | |||||
b: result[2] | |||||
}; | |||||
return _cache[val]; | |||||
} | |||||
function interpolateColors(c1, c2, p) { | |||||
c1 = parseColor(c1); | |||||
c2 = parseColor(c2); | |||||
var c = { | |||||
r: c1.r * (1 - p) + c2.r * p, | |||||
g: c1.g * (1 - p) + c2.g * p, | |||||
b: c1.b * (1 - p) + c2.b * p | |||||
}; | |||||
return 'rgb(' + [c.r | 0, c.g | 0, c.b | 0].join(',') + ')'; | |||||
} | |||||
/** | |||||
* This function will animate some specified node properties. It will | |||||
* basically call requestAnimationFrame, interpolate the values and call the | |||||
* refresh method during a specified duration. | |||||
* | |||||
* Recognized parameters: | |||||
* ********************** | |||||
* Here is the exhaustive list of every accepted parameters in the settings | |||||
* object: | |||||
* | |||||
* {?array} nodes An array of node objects or node ids. If | |||||
* not specified, all nodes of the graph | |||||
* will be animated. | |||||
* {?(function|string)} easing Either the name of an easing in the | |||||
* sigma.utils.easings package or a | |||||
* function. If not specified, the | |||||
* quadraticInOut easing from this package | |||||
* will be used instead. | |||||
* {?number} duration The duration of the animation. If not | |||||
* specified, the "animationsTime" setting | |||||
* value of the sigma instance will be used | |||||
* instead. | |||||
* {?function} onComplete Eventually a function to call when the | |||||
* animation is ended. | |||||
* | |||||
* @param {sigma} s The related sigma instance. | |||||
* @param {object} animate An hash with the keys being the node properties | |||||
* to interpolate, and the values being the related | |||||
* target values. | |||||
* @param {?object} options Eventually an object with options. | |||||
*/ | |||||
sigma.plugins.animate = function(s, animate, options) { | |||||
var o = options || {}, | |||||
id = ++_id, | |||||
duration = o.duration || s.settings('animationsTime'), | |||||
easing = typeof o.easing === 'string' ? | |||||
sigma.utils.easings[o.easing] : | |||||
typeof o.easing === 'function' ? | |||||
o.easing : | |||||
sigma.utils.easings.quadraticInOut, | |||||
start = sigma.utils.dateNow(), | |||||
nodes, | |||||
startPositions; | |||||
if (o.nodes && o.nodes.length) { | |||||
if (typeof o.nodes[0] === 'object') | |||||
nodes = o.nodes; | |||||
else | |||||
nodes = s.graph.nodes(o.nodes); // argument is an array of IDs | |||||
} | |||||
else | |||||
nodes = s.graph.nodes(); | |||||
// Store initial positions: | |||||
startPositions = nodes.reduce(function(res, node) { | |||||
var k; | |||||
res[node.id] = {}; | |||||
for (k in animate) | |||||
if (k in node) | |||||
res[node.id][k] = node[k]; | |||||
return res; | |||||
}, {}); | |||||
s.animations = s.animations || Object.create({}); | |||||
sigma.plugins.kill(s); | |||||
// Do not refresh edgequadtree during drag: | |||||
var k, | |||||
c; | |||||
for (k in s.cameras) { | |||||
c = s.cameras[k]; | |||||
c.edgequadtree._enabled = false; | |||||
} | |||||
function step() { | |||||
var p = (sigma.utils.dateNow() - start) / duration; | |||||
if (p >= 1) { | |||||
nodes.forEach(function(node) { | |||||
for (var k in animate) | |||||
if (k in animate) | |||||
node[k] = node[animate[k]]; | |||||
}); | |||||
// Allow to refresh edgequadtree: | |||||
var k, | |||||
c; | |||||
for (k in s.cameras) { | |||||
c = s.cameras[k]; | |||||
c.edgequadtree._enabled = true; | |||||
} | |||||
s.refresh(); | |||||
if (typeof o.onComplete === 'function') | |||||
o.onComplete(); | |||||
} else { | |||||
p = easing(p); | |||||
nodes.forEach(function(node) { | |||||
for (var k in animate) | |||||
if (k in animate) { | |||||
if (k.match(/color$/)) | |||||
node[k] = interpolateColors( | |||||
startPositions[node.id][k], | |||||
node[animate[k]], | |||||
p | |||||
); | |||||
else | |||||
node[k] = | |||||
node[animate[k]] * p + | |||||
startPositions[node.id][k] * (1 - p); | |||||
} | |||||
}); | |||||
s.refresh(); | |||||
s.animations[id] = requestAnimationFrame(step); | |||||
} | |||||
} | |||||
step(); | |||||
}; | |||||
sigma.plugins.kill = function(s) { | |||||
for (var k in (s.animations || {})) | |||||
cancelAnimationFrame(s.animations[k]); | |||||
// Allow to refresh edgequadtree: | |||||
var k, | |||||
c; | |||||
for (k in s.cameras) { | |||||
c = s.cameras[k]; | |||||
c.edgequadtree._enabled = true; | |||||
} | |||||
}; | |||||
}).call(window); |
@ -0,0 +1,36 @@ | |||||
sigma.plugins.dragNodes | |||||
===================== | |||||
Plugin developed by [José M. Camacho](https://github.com/josemazo), events by [Sébastien Heymann](https://github.com/sheymann) for [Linkurious](https://github.com/Linkurious). | |||||
--- | |||||
This plugin provides a method to drag & drop nodes. At the moment, this plugin is not compatible with the WebGL renderer. Check the sigma.plugins.dragNodes function doc or the [example code](../../examples/drag-nodes.html) to know more. | |||||
To use, include all .js files under this folder. Then initialize it as follows: | |||||
````javascript | |||||
var dragListener = new sigma.plugins.dragNodes(sigInst, renderer); | |||||
```` | |||||
Kill the plugin as follows: | |||||
````javascript | |||||
sigma.plugins.killDragNodes(sigInst); | |||||
```` | |||||
## Events | |||||
This plugin provides the following events fired by the instance of the plugin: | |||||
* `startdrag`: fired at the beginning of the drag | |||||
* `drag`: fired while the node is dragged | |||||
* `drop`: fired at the end of the drag if the node has been dragged | |||||
* `dragend`: fired at the end of the drag | |||||
Exemple of event binding: | |||||
````javascript | |||||
dragListener.bind('startdrag', function(event) { | |||||
console.log(event); | |||||
}); | |||||
```` |
@ -0,0 +1,326 @@ | |||||
/** | |||||
* This plugin provides a method to drag & drop nodes. Check the | |||||
* sigma.plugins.dragNodes function doc or the examples/basic.html & | |||||
* examples/api-candy.html code samples to know more. | |||||
*/ | |||||
(function() { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
sigma.utils.pkg('sigma.plugins'); | |||||
/** | |||||
* This function will add `mousedown`, `mouseup` & `mousemove` events to the | |||||
* nodes in the `overNode`event to perform drag & drop operations. It uses | |||||
* `linear interpolation` [http://en.wikipedia.org/wiki/Linear_interpolation] | |||||
* and `rotation matrix` [http://en.wikipedia.org/wiki/Rotation_matrix] to | |||||
* calculate the X and Y coordinates from the `cam` or `renderer` node | |||||
* attributes. These attributes represent the coordinates of the nodes in | |||||
* the real container, not in canvas. | |||||
* | |||||
* Fired events: | |||||
* ************* | |||||
* startdrag Fired at the beginning of the drag. | |||||
* drag Fired while the node is dragged. | |||||
* drop Fired at the end of the drag if the node has been dragged. | |||||
* dragend Fired at the end of the drag. | |||||
* | |||||
* Recognized parameters: | |||||
* ********************** | |||||
* @param {sigma} s The related sigma instance. | |||||
* @param {renderer} renderer The related renderer instance. | |||||
*/ | |||||
function DragNodes(s, renderer) { | |||||
sigma.classes.dispatcher.extend(this); | |||||
// A quick hardcoded rule to prevent people from using this plugin with the | |||||
// WebGL renderer (which is impossible at the moment): | |||||
// if ( | |||||
// sigma.renderers.webgl && | |||||
// renderer instanceof sigma.renderers.webgl | |||||
// ) | |||||
// throw new Error( | |||||
// 'The sigma.plugins.dragNodes is not compatible with the WebGL renderer' | |||||
// ); | |||||
// Init variables: | |||||
var _self = this, | |||||
_s = s, | |||||
_body = document.body, | |||||
_renderer = renderer, | |||||
_mouse = renderer.container.lastChild, | |||||
_camera = renderer.camera, | |||||
_node = null, | |||||
_prefix = '', | |||||
_hoverStack = [], | |||||
_hoverIndex = {}, | |||||
_isMouseDown = false, | |||||
_isMouseOverCanvas = false, | |||||
_drag = false; | |||||
if (renderer instanceof sigma.renderers.svg) { | |||||
_mouse = renderer.container.firstChild; | |||||
} | |||||
// It removes the initial substring ('read_') if it's a WegGL renderer. | |||||
if (renderer instanceof sigma.renderers.webgl) { | |||||
_prefix = renderer.options.prefix.substr(5); | |||||
} else { | |||||
_prefix = renderer.options.prefix; | |||||
} | |||||
renderer.bind('overNode', nodeMouseOver); | |||||
renderer.bind('outNode', treatOutNode); | |||||
renderer.bind('click', click); | |||||
_s.bind('kill', function() { | |||||
_self.unbindAll(); | |||||
}); | |||||
/** | |||||
* Unbind all event listeners. | |||||
*/ | |||||
this.unbindAll = function() { | |||||
_mouse.removeEventListener('mousedown', nodeMouseDown); | |||||
_body.removeEventListener('mousemove', nodeMouseMove); | |||||
_body.removeEventListener('mouseup', nodeMouseUp); | |||||
_renderer.unbind('overNode', nodeMouseOver); | |||||
_renderer.unbind('outNode', treatOutNode); | |||||
} | |||||
// Calculates the global offset of the given element more accurately than | |||||
// element.offsetTop and element.offsetLeft. | |||||
function calculateOffset(element) { | |||||
var style = window.getComputedStyle(element); | |||||
var getCssProperty = function(prop) { | |||||
return parseInt(style.getPropertyValue(prop).replace('px', '')) || 0; | |||||
}; | |||||
return { | |||||
left: element.getBoundingClientRect().left + getCssProperty('padding-left'), | |||||
top: element.getBoundingClientRect().top + getCssProperty('padding-top') | |||||
}; | |||||
}; | |||||
function click(event) { | |||||
// event triggered at the end of the click | |||||
_isMouseDown = false; | |||||
_body.removeEventListener('mousemove', nodeMouseMove); | |||||
_body.removeEventListener('mouseup', nodeMouseUp); | |||||
if (!_hoverStack.length) { | |||||
_node = null; | |||||
} | |||||
}; | |||||
function nodeMouseOver(event) { | |||||
// Don't treat the node if it is already registered | |||||
if (_hoverIndex[event.data.node.id]) { | |||||
return; | |||||
} | |||||
// Add node to array of current nodes over | |||||
_hoverStack.push(event.data.node); | |||||
_hoverIndex[event.data.node.id] = true; | |||||
if(_hoverStack.length && ! _isMouseDown) { | |||||
// Set the current node to be the last one in the array | |||||
_node = _hoverStack[_hoverStack.length - 1]; | |||||
_mouse.addEventListener('mousedown', nodeMouseDown); | |||||
} | |||||
}; | |||||
function treatOutNode(event) { | |||||
// Remove the node from the array | |||||
var indexCheck = _hoverStack.map(function(e) { return e; }).indexOf(event.data.node); | |||||
_hoverStack.splice(indexCheck, 1); | |||||
delete _hoverIndex[event.data.node.id]; | |||||
if(_hoverStack.length && ! _isMouseDown) { | |||||
// On out, set the current node to be the next stated in array | |||||
_node = _hoverStack[_hoverStack.length - 1]; | |||||
} else { | |||||
_mouse.removeEventListener('mousedown', nodeMouseDown); | |||||
} | |||||
}; | |||||
function nodeMouseDown(event) { | |||||
_isMouseDown = true; | |||||
var size = _s.graph.nodes().length; | |||||
// when there is only node in the graph, the plugin cannot apply | |||||
// linear interpolation. So treat it as if a user is dragging | |||||
// the graph | |||||
if (_node && size > 1) { | |||||
_mouse.removeEventListener('mousedown', nodeMouseDown); | |||||
_body.addEventListener('mousemove', nodeMouseMove); | |||||
_body.addEventListener('mouseup', nodeMouseUp); | |||||
// Do not refresh edgequadtree during drag: | |||||
var k, | |||||
c; | |||||
for (k in _s.cameras) { | |||||
c = _s.cameras[k]; | |||||
if (c.edgequadtree !== undefined) { | |||||
c.edgequadtree._enabled = false; | |||||
} | |||||
} | |||||
// Deactivate drag graph. | |||||
_renderer.settings({mouseEnabled: false, enableHovering: false}); | |||||
_s.refresh(); | |||||
_self.dispatchEvent('startdrag', { | |||||
node: _node, | |||||
captor: event, | |||||
renderer: _renderer | |||||
}); | |||||
} | |||||
}; | |||||
function nodeMouseUp(event) { | |||||
_isMouseDown = false; | |||||
_mouse.addEventListener('mousedown', nodeMouseDown); | |||||
_body.removeEventListener('mousemove', nodeMouseMove); | |||||
_body.removeEventListener('mouseup', nodeMouseUp); | |||||
// Allow to refresh edgequadtree: | |||||
var k, | |||||
c; | |||||
for (k in _s.cameras) { | |||||
c = _s.cameras[k]; | |||||
if (c.edgequadtree !== undefined) { | |||||
c.edgequadtree._enabled = true; | |||||
} | |||||
} | |||||
// Activate drag graph. | |||||
_renderer.settings({mouseEnabled: true, enableHovering: true}); | |||||
_s.refresh(); | |||||
if (_drag) { | |||||
_self.dispatchEvent('drop', { | |||||
node: _node, | |||||
captor: event, | |||||
renderer: _renderer | |||||
}); | |||||
} | |||||
_self.dispatchEvent('dragend', { | |||||
node: _node, | |||||
captor: event, | |||||
renderer: _renderer | |||||
}); | |||||
_drag = false; | |||||
_node = null; | |||||
}; | |||||
function nodeMouseMove(event) { | |||||
if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { | |||||
clearTimeout(timeOut); | |||||
var timeOut = setTimeout(executeNodeMouseMove, 0); | |||||
} else { | |||||
executeNodeMouseMove(); | |||||
} | |||||
function executeNodeMouseMove() { | |||||
var offset = calculateOffset(_renderer.container), | |||||
x = event.clientX - offset.left, | |||||
y = event.clientY - offset.top, | |||||
cos = Math.cos(_camera.angle), | |||||
sin = Math.sin(_camera.angle), | |||||
nodes = _s.graph.nodes(), | |||||
ref = []; | |||||
// Getting and derotating the reference coordinates. | |||||
for (var i = 0; i < 2; i++) { | |||||
var n = nodes[i]; | |||||
var aux = { | |||||
x: n.x * cos + n.y * sin, | |||||
y: n.y * cos - n.x * sin, | |||||
renX: n[_prefix + 'x'], | |||||
renY: n[_prefix + 'y'], | |||||
}; | |||||
ref.push(aux); | |||||
} | |||||
// Applying linear interpolation. | |||||
// if the nodes are on top of each other, we use the camera ratio to interpolate | |||||
if (ref[0].x === ref[1].x && ref[0].y === ref[1].y) { | |||||
var xRatio = (ref[0].renX === 0) ? 1 : ref[0].renX; | |||||
var yRatio = (ref[0].renY === 0) ? 1 : ref[0].renY; | |||||
x = (ref[0].x / xRatio) * (x - ref[0].renX) + ref[0].x; | |||||
y = (ref[0].y / yRatio) * (y - ref[0].renY) + ref[0].y; | |||||
} else { | |||||
var xRatio = (ref[1].renX - ref[0].renX) / (ref[1].x - ref[0].x); | |||||
var yRatio = (ref[1].renY - ref[0].renY) / (ref[1].y - ref[0].y); | |||||
// if the coordinates are the same, we use the other ratio to interpolate | |||||
if (ref[1].x === ref[0].x) { | |||||
xRatio = yRatio; | |||||
} | |||||
if (ref[1].y === ref[0].y) { | |||||
yRatio = xRatio; | |||||
} | |||||
x = (x - ref[0].renX) / xRatio + ref[0].x; | |||||
y = (y - ref[0].renY) / yRatio + ref[0].y; | |||||
} | |||||
// Rotating the coordinates. | |||||
_node.x = x * cos - y * sin; | |||||
_node.y = y * cos + x * sin; | |||||
_s.refresh(); | |||||
_drag = true; | |||||
_self.dispatchEvent('drag', { | |||||
node: _node, | |||||
captor: event, | |||||
renderer: _renderer | |||||
}); | |||||
} | |||||
}; | |||||
}; | |||||
/** | |||||
* Interface | |||||
* ------------------ | |||||
* | |||||
* > var dragNodesListener = sigma.plugins.dragNodes(s, s.renderers[0]); | |||||
*/ | |||||
var _instance = {}; | |||||
/** | |||||
* @param {sigma} s The related sigma instance. | |||||
* @param {renderer} renderer The related renderer instance. | |||||
*/ | |||||
sigma.plugins.dragNodes = function(s, renderer) { | |||||
// Create object if undefined | |||||
if (!_instance[s.id]) { | |||||
_instance[s.id] = new DragNodes(s, renderer); | |||||
} | |||||
s.bind('kill', function() { | |||||
sigma.plugins.killDragNodes(s); | |||||
}); | |||||
return _instance[s.id]; | |||||
}; | |||||
/** | |||||
* This method removes the event listeners and kills the dragNodes instance. | |||||
* | |||||
* @param {sigma} s The related sigma instance. | |||||
*/ | |||||
sigma.plugins.killDragNodes = function(s) { | |||||
if (_instance[s.id] instanceof DragNodes) { | |||||
_instance[s.id].unbindAll(); | |||||
delete _instance[s.id]; | |||||
} | |||||
}; | |||||
}).call(window); |
@ -0,0 +1,187 @@ | |||||
sigma.plugins.filter | |||||
================== | |||||
Plugin developed by [Sébastien Heymann](sheymann) for [Linkurious](https://github.com/Linkurious). | |||||
--- | |||||
## General | |||||
This plugin filters nodes and edges in a fancy manner: | |||||
- Define your own filters on nodes and edges using the `nodesBy` and `edgesBy` methods, or execute more complex filters using the `neighborsOf` method. | |||||
- Register multiple filters before applying them anytime at once. | |||||
- Undo any filter while preserving the execution order. | |||||
- Chain all methods for concise style. | |||||
See the following [example code](../../examples/filters.html) and [unit tests](../../test/unit.plugins.filter.js) for full usage. | |||||
To use, include all .js files under this folder. Then initialize it as follows: | |||||
````javascript | |||||
var filter = new sigma.plugins.filter(sigInst); | |||||
```` | |||||
## Predicates | |||||
Predicates are truth tests (i.e. functions which return a boolean) on a single node or a single edge. They return true if the element should be visible. For instance: | |||||
````javascript | |||||
// Only edges of size above one should be visible: | |||||
function(e) { | |||||
return e.size > 1; | |||||
} | |||||
```` | |||||
In this example, notice that if the size attribute is undefined, the edge will be hidden. If you still want to display edges with no size attribute defined, you have to modify the predicate a bit: | |||||
````javascript | |||||
// Only edges of size above one should be visible: | |||||
function(e) { | |||||
return e.size === undefined || e.size > 1; | |||||
} | |||||
```` | |||||
Predicates are applied by predicate processors. | |||||
## Predicate processors | |||||
Predicate processors are functions which wrap one predicate and apply it to the graph. Three predicate processors are available: | |||||
- `nodesBy` | |||||
- `edgesBy` | |||||
- `neighborsOf` | |||||
For each node of the graph, the `nodesBy` processor sets the attribute `hidden` to false if the predicate is true for the node. It also sets the `hidden` attribute of edges to true if one of the edge's extremities is hidden. For instance: | |||||
````javascript | |||||
// Only connected nodes (i.e. nodes of positive degree) should be visible: | |||||
filter.nodesBy(function(n) { | |||||
return this.degree(n.id) > 0; | |||||
}, 'non-isolates'); | |||||
```` | |||||
For each edge of the graph, the `edgesBy` processor sets the attribute `hidden` to false if the predicate is true for the edge. For instance: | |||||
````javascript | |||||
// Only edges of size above one should be visible: | |||||
filter.edgesBy(function(e) { | |||||
return e.size > 1; | |||||
}, 'edge-size-above-one'); | |||||
```` | |||||
For each neighbor node of a specified node, the `neighborsOf` processor sets the attribute `hidden` to true if it is not directly connected to the node. It also sets the `hidden` attribute of edges to true if one of the edge's extremities is hidden. For instance: | |||||
````javascript | |||||
// Only neighbors of the node 'n0' should be visible: | |||||
filter.neighborsOf('n0'); | |||||
```` | |||||
Processors instanciated with a predicate are called filters. **Filters are not applied until the `apply` method is called.** | |||||
## Filters chain | |||||
Combining filters is easy! Declare one filter after another, then call the `apply` method to execute them on the graph in that order. For instance: | |||||
````javascript | |||||
// graph = { | |||||
// nodes: [{id:'n0'}, {id:'n1'}, {id:'n2'}, {id:'n3'}], | |||||
// edges: [ | |||||
// {id:'e0', source:'n0', target:'n1', size:1}, | |||||
// {id:'e1', source:'n1', target:'n2', size:0.5}, | |||||
// {id:'e2', source:'n1', target:'n2'}] | |||||
// } | |||||
filter | |||||
.nodesBy(function(n) { | |||||
return this.degree(n.id) > 0; | |||||
}) | |||||
.edgesBy(function(e) { | |||||
return e.size >= 1; | |||||
}) | |||||
.apply(); | |||||
// n3.hidden == true | |||||
// e1.hidden == true | |||||
// e2.hidden == true | |||||
```` | |||||
Combined filters work like if there was an 'AND' operator between them. Be careful not to create mutually exclusive filters, for instance: | |||||
````javascript | |||||
filter | |||||
.nodesBy(function(n) { | |||||
return n.attributes.animal === 'pony'; | |||||
}) | |||||
.nodesBy(function(n) { | |||||
return n.attributes.animal !== 'pony'; | |||||
}) | |||||
.apply(); | |||||
// all nodes are hidden | |||||
```` | |||||
Filters are internally stored in an array called the `chain`. | |||||
## Undo filters | |||||
Undoing filters means to remove them from the `chain`. Filters can be undone easily. Choose which filter(s) to undo, or undo all of them at once. | |||||
Filters can be associated with keys at declaration, where keys are any string you give. For instance, the following filter has the key *node-animal*: | |||||
````javascript | |||||
filter.nodesBy(function(n) { | |||||
return n.attributes.animal === 'pony'; | |||||
}, 'node-animal'); | |||||
```` | |||||
Manually undo this filter as follows: | |||||
````javascript | |||||
filter | |||||
.undo('node-animal') | |||||
.apply(); // we want it applied now | |||||
```` | |||||
Multiple filters can be undone at once, for instance: | |||||
````javascript | |||||
filter.undo('node-animal', 'edge-size', 'high-node-degree'); | |||||
// don't forget to call `apply()` anytime! | |||||
```` | |||||
Alternative syntax: | |||||
````javascript | |||||
var a = ['node-animal', 'edge-size', 'high-node-degree']; | |||||
filter.undo(a); | |||||
// don't forget to call `apply()` anytime! | |||||
```` | |||||
Finally, undo all filters (with or without keys) as follows: | |||||
````javascript | |||||
filter.undo(); | |||||
// don't forget to call `apply()` anytime! | |||||
```` | |||||
Warning: you can't declare two filters with the same key, or it will throw an exception. | |||||
## Export the chain | |||||
The exported chain is an array of objects. Each object represents a filter by a triplet *(?key, processor, predicate)*. The processor value is the internal name of the processor: `filter.processors.nodes`, `filter.processors.edges`, `filter.processors.neighbors`. The predicate value is a copy of the predicate function. Dump the `chain` using the `export` method as follows: | |||||
````javascript | |||||
var chain = filter.export(); | |||||
// chain == [ | |||||
// { | |||||
// key: '...', | |||||
// processor: '...', | |||||
// predicate: function() {...} | |||||
// }, ... | |||||
// ] | |||||
```` | |||||
## Import a chain | |||||
You can load a filters chain using the `import` method: | |||||
````javascript | |||||
var chain = [ | |||||
{ | |||||
key: 'my-filter', | |||||
predicate: function(n) { return this.degree(n.id) > 0; }, | |||||
processor: 'filter.processors.nodes' | |||||
} | |||||
]; | |||||
filter | |||||
.import(chain) | |||||
.apply(); | |||||
```` |
@ -0,0 +1,504 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.plugins'); | |||||
// Add custom graph methods: | |||||
/** | |||||
* This methods returns an array of nodes that are adjacent to a node. | |||||
* | |||||
* @param {string} id The node id. | |||||
* @return {array} The array of adjacent nodes. | |||||
*/ | |||||
if (!sigma.classes.graph.hasMethod('adjacentNodes')) | |||||
sigma.classes.graph.addMethod('adjacentNodes', function(id) { | |||||
if (typeof id !== 'string') | |||||
throw 'adjacentNodes: the node id must be a string.'; | |||||
var target, | |||||
nodes = []; | |||||
for(target in this.allNeighborsIndex[id]) { | |||||
nodes.push(this.nodesIndex[target]); | |||||
} | |||||
return nodes; | |||||
}); | |||||
/** | |||||
* This methods returns an array of edges that are adjacent to a node. | |||||
* | |||||
* @param {string} id The node id. | |||||
* @return {array} The array of adjacent edges. | |||||
*/ | |||||
if (!sigma.classes.graph.hasMethod('adjacentEdges')) | |||||
sigma.classes.graph.addMethod('adjacentEdges', function(id) { | |||||
if (typeof id !== 'string') | |||||
throw 'adjacentEdges: the node id must be a string.'; | |||||
var a = this.allNeighborsIndex[id], | |||||
eid, | |||||
target, | |||||
edges = []; | |||||
for(target in a) { | |||||
for(eid in a[target]) { | |||||
edges.push(a[target][eid]); | |||||
} | |||||
} | |||||
return edges; | |||||
}); | |||||
/** | |||||
* Sigma Filter | |||||
* ============================= | |||||
* | |||||
* @author Sébastien Heymann <seb@linkurio.us> (Linkurious) | |||||
* @version 0.1 | |||||
*/ | |||||
var _g = undefined, | |||||
_s = undefined, | |||||
_chain = [], // chain of wrapped filters | |||||
_keysIndex = Object.create(null), | |||||
Processors = {}; // available predicate processors | |||||
/** | |||||
* Library of processors | |||||
* ------------------ | |||||
*/ | |||||
/** | |||||
* | |||||
* @param {function} fn The predicate. | |||||
*/ | |||||
Processors.nodes = function nodes(fn) { | |||||
var n = _g.nodes(), | |||||
ln = n.length, | |||||
e = _g.edges(), | |||||
le = e.length; | |||||
// hide node, or keep former value | |||||
while(ln--) | |||||
n[ln].hidden = !fn.call(_g, n[ln]) || n[ln].hidden; | |||||
while(le--) | |||||
if (_g.nodes(e[le].source).hidden || _g.nodes(e[le].target).hidden) | |||||
e[le].hidden = true; | |||||
}; | |||||
/** | |||||
* | |||||
* @param {function} fn The predicate. | |||||
*/ | |||||
Processors.edges = function edges(fn) { | |||||
var e = _g.edges(), | |||||
le = e.length; | |||||
// hide edge, or keep former value | |||||
while(le--) | |||||
e[le].hidden = !fn.call(_g, e[le]) || e[le].hidden; | |||||
}; | |||||
/** | |||||
* | |||||
* @param {string} id The center node. | |||||
*/ | |||||
Processors.neighbors = function neighbors(id) { | |||||
var n = _g.nodes(), | |||||
ln = n.length, | |||||
e = _g.edges(), | |||||
le = e.length, | |||||
neighbors = _g.adjacentNodes(id), | |||||
nn = neighbors.length, | |||||
no = {}; | |||||
while(nn--) | |||||
no[neighbors[nn].id] = true; | |||||
while(ln--) | |||||
if (n[ln].id !== id && !(n[ln].id in no)) | |||||
n[ln].hidden = true; | |||||
while(le--) | |||||
if (_g.nodes(e[le].source).hidden || _g.nodes(e[le].target).hidden) | |||||
e[le].hidden = true; | |||||
}; | |||||
/** | |||||
* This function adds a filter to the chain of filters. | |||||
* | |||||
* @param {function} fn The filter (i.e. predicate processor). | |||||
* @param {function} p The predicate. | |||||
* @param {?string} key The key to identify the filter. | |||||
*/ | |||||
function register(fn, p, key) { | |||||
if (key != undefined && typeof key !== 'string') | |||||
throw 'The filter key "'+ key.toString() +'" must be a string.'; | |||||
if (key != undefined && !key.length) | |||||
throw 'The filter key must be a non-empty string.'; | |||||
if (typeof fn !== 'function') | |||||
throw 'The predicate of key "'+ key +'" must be a function.'; | |||||
if ('undo' === key) | |||||
throw '"undo" is a reserved key.'; | |||||
if (_keysIndex[key]) | |||||
throw 'The filter "' + key + '" already exists.'; | |||||
if (key) | |||||
_keysIndex[key] = true; | |||||
_chain.push({ | |||||
'key': key, | |||||
'processor': fn, | |||||
'predicate': p | |||||
}); | |||||
}; | |||||
/** | |||||
* This function removes a set of filters from the chain. | |||||
* | |||||
* @param {object} o The filter keys. | |||||
*/ | |||||
function unregister (o) { | |||||
_chain = _chain.filter(function(a) { | |||||
return !(a.key in o); | |||||
}); | |||||
for(var key in o) | |||||
delete _keysIndex[key]; | |||||
}; | |||||
/** | |||||
* Filter Object | |||||
* ------------------ | |||||
* @param {sigma} s The related sigma instance. | |||||
*/ | |||||
function Filter(s) { | |||||
_s = s; | |||||
_g = s.graph; | |||||
}; | |||||
/** | |||||
* This method is used to filter the nodes. The method must be called with | |||||
* the predicate, which is a function that takes a node as argument and | |||||
* returns a boolean. It may take an identifier as argument to undo the | |||||
* filter later. The method wraps the predicate into an anonymous function | |||||
* that looks through each node in the graph. When executed, the anonymous | |||||
* function hides the nodes that fail a truth test (predicate). The method | |||||
* adds the anonymous function to the chain of filters. The filter is not | |||||
* executed until the apply() method is called. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > filter.nodesBy(function(n) { | |||||
* > return this.degree(n.id) > 0; | |||||
* > }, 'degreeNotNull'); | |||||
* | |||||
* @param {function} fn The filter predicate. | |||||
* @param {?string} key The key to identify the filter. | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.nodesBy = function(fn, key) { | |||||
// Wrap the predicate to be applied on the graph and add it to the chain. | |||||
register(Processors.nodes, fn, key); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method is used to filter the edges. The method must be called with | |||||
* the predicate, which is a function that takes a node as argument and | |||||
* returns a boolean. It may take an identifier as argument to undo the | |||||
* filter later. The method wraps the predicate into an anonymous function | |||||
* that looks through each edge in the graph. When executed, the anonymous | |||||
* function hides the edges that fail a truth test (predicate). The method | |||||
* adds the anonymous function to the chain of filters. The filter is not | |||||
* executed until the apply() method is called. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > filter.edgesBy(function(e) { | |||||
* > return e.size > 1; | |||||
* > }, 'edgeSize'); | |||||
* | |||||
* @param {function} fn The filter predicate. | |||||
* @param {?string} key The key to identify the filter. | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.edgesBy = function(fn, key) { | |||||
// Wrap the predicate to be applied on the graph and add it to the chain. | |||||
register(Processors.edges, fn, key); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method is used to filter the nodes which are not direct connections | |||||
* of a given node. The method must be called with the node identifier. It | |||||
* may take an identifier as argument to undo the filter later. The filter | |||||
* is not executed until the apply() method is called. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > filter.neighborsOf('n0'); | |||||
* | |||||
* @param {string} id The node id. | |||||
* @param {?string} key The key to identify the filter. | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.neighborsOf = function(id, key) { | |||||
if (typeof id !== 'string') | |||||
throw 'The node id "'+ id.toString() +'" must be a string.'; | |||||
if (!id.length) | |||||
throw 'The node id must be a non-empty string.'; | |||||
// Wrap the predicate to be applied on the graph and add it to the chain. | |||||
register(Processors.neighbors, id, key); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method is used to execute the chain of filters and to refresh the | |||||
* display. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > filter | |||||
* > .nodesBy(function(n) { | |||||
* > return this.degree(n.id) > 0; | |||||
* > }, 'degreeNotNull') | |||||
* > .apply(); | |||||
* | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.apply = function() { | |||||
for (var i = 0, len = _chain.length; i < len; ++i) { | |||||
_chain[i].processor(_chain[i].predicate); | |||||
}; | |||||
if (_chain[0] && 'undo' === _chain[0].key) { | |||||
_chain.shift(); | |||||
} | |||||
_s.refresh(); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method undoes one or several filters, depending on how it is called. | |||||
* | |||||
* To undo all filters, call "undo" without argument. To undo a specific | |||||
* filter, call it with the key of the filter. To undo multiple filters, call | |||||
* it with an array of keys or multiple arguments, and it will undo each | |||||
* filter, in the same order. The undo is not executed until the apply() | |||||
* method is called. For instance: | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > filter | |||||
* > .nodesBy(function(n) { | |||||
* > return this.degree(n.id) > 0; | |||||
* > }, 'degreeNotNull'); | |||||
* > .edgesBy(function(e) { | |||||
* > return e.size > 1; | |||||
* > }, 'edgeSize') | |||||
* > .undo(); | |||||
* | |||||
* Other examples: | |||||
* > filter.undo(); | |||||
* > filter.undo('myfilter'); | |||||
* > filter.undo(['myfilter1', 'myfilter2']); | |||||
* > filter.undo('myfilter1', 'myfilter2'); | |||||
* | |||||
* @param {?(string|array|*string))} v Eventually one key, an array of keys. | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.undo = function(v) { | |||||
var q = Object.create(null), | |||||
la = arguments.length; | |||||
// find removable filters | |||||
if (la === 1) { | |||||
if (Object.prototype.toString.call(v) === '[object Array]') | |||||
for (var i = 0, len = v.length; i < len; i++) | |||||
q[v[i]] = true; | |||||
else // 1 filter key | |||||
q[v] = true; | |||||
} else if (la > 1) { | |||||
for (var i = 0; i < la; i++) | |||||
q[arguments[i]] = true; | |||||
} | |||||
else | |||||
this.clear(); | |||||
unregister(q); | |||||
function processor() { | |||||
var n = _g.nodes(), | |||||
ln = n.length, | |||||
e = _g.edges(), | |||||
le = e.length; | |||||
while(ln--) | |||||
n[ln].hidden = false; | |||||
while(le--) | |||||
e[le].hidden = false; | |||||
}; | |||||
_chain.unshift({ | |||||
'key': 'undo', | |||||
'processor': processor | |||||
}); | |||||
return this; | |||||
}; | |||||
// fast deep copy function | |||||
function deepCopy(o) { | |||||
var copy = Object.create(null); | |||||
for (var i in o) { | |||||
if (typeof o[i] === "object" && o[i] !== null) { | |||||
copy[i] = deepCopy(o[i]); | |||||
} | |||||
else if (typeof o[i] === "function" && o[i] !== null) { | |||||
// clone function: | |||||
eval(" copy[i] = " + o[i].toString()); | |||||
//copy[i] = o[i].bind(_g); | |||||
} | |||||
else | |||||
copy[i] = o[i]; | |||||
} | |||||
return copy; | |||||
}; | |||||
function cloneChain(chain) { | |||||
// Clone the array of filters: | |||||
var copy = chain.slice(0); | |||||
for (var i = 0, len = copy.length; i < len; i++) { | |||||
copy[i] = deepCopy(copy[i]); | |||||
if (typeof copy[i].processor === "function") | |||||
copy[i].processor = 'filter.processors.' + copy[i].processor.name; | |||||
}; | |||||
return copy; | |||||
} | |||||
/** | |||||
* This method is used to empty the chain of filters. | |||||
* Prefer the undo() method to reset filters. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > filter.clear(); | |||||
* | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.clear = function() { | |||||
_chain.length = 0; // clear the array | |||||
_keysIndex = Object.create(null); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method clones the filter chain and return the copy. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > var chain = filter.export(); | |||||
* | |||||
* @return {object} The cloned chain of filters. | |||||
*/ | |||||
Filter.prototype.export = function() { | |||||
var c = cloneChain(_chain); | |||||
return c; | |||||
}; | |||||
/** | |||||
* This method sets the chain of filters with the specified chain. | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
* > var chain = [ | |||||
* > { | |||||
* > key: 'my-filter', | |||||
* > predicate: function(n) {...}, | |||||
* > processor: 'filter.processors.nodes' | |||||
* > }, ... | |||||
* > ]; | |||||
* > filter.import(chain); | |||||
* | |||||
* @param {array} chain The chain of filters. | |||||
* @return {sigma.plugins.filter} Returns the instance. | |||||
*/ | |||||
Filter.prototype.import = function(chain) { | |||||
if (chain === undefined) | |||||
throw 'Wrong arguments.'; | |||||
if (Object.prototype.toString.call(chain) !== '[object Array]') | |||||
throw 'The chain" must be an array.'; | |||||
var copy = cloneChain(chain); | |||||
for (var i = 0, len = copy.length; i < len; i++) { | |||||
if (copy[i].predicate === undefined || copy[i].processor === undefined) | |||||
throw 'Wrong arguments.'; | |||||
if (copy[i].key != undefined && typeof copy[i].key !== 'string') | |||||
throw 'The filter key "'+ copy[i].key.toString() +'" must be a string.'; | |||||
if (typeof copy[i].predicate !== 'function') | |||||
throw 'The predicate of key "'+ copy[i].key +'" must be a function.'; | |||||
if (typeof copy[i].processor !== 'string') | |||||
throw 'The processor of key "'+ copy[i].key +'" must be a string.'; | |||||
// Replace the processor name by the corresponding function: | |||||
switch(copy[i].processor) { | |||||
case 'filter.processors.nodes': | |||||
copy[i].processor = Processors.nodes; | |||||
break; | |||||
case 'filter.processors.edges': | |||||
copy[i].processor = Processors.edges; | |||||
break; | |||||
case 'filter.processors.neighbors': | |||||
copy[i].processor = Processors.neighbors; | |||||
break; | |||||
default: | |||||
throw 'Unknown processor ' + copy[i].processor; | |||||
} | |||||
}; | |||||
_chain = copy; | |||||
return this; | |||||
}; | |||||
/** | |||||
* Interface | |||||
* ------------------ | |||||
* | |||||
* > var filter = new sigma.plugins.filter(s); | |||||
*/ | |||||
var filter = null; | |||||
/** | |||||
* @param {sigma} s The related sigma instance. | |||||
*/ | |||||
sigma.plugins.filter = function(s) { | |||||
// Create filter if undefined | |||||
if (!filter) { | |||||
filter = new Filter(s); | |||||
} | |||||
return filter; | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,24 @@ | |||||
sigma.plugins.neighborhood | |||||
========================== | |||||
Plugin developed by [Alexis Jacomy](https://github.com/jacomyal). | |||||
--- | |||||
This plugin provides a method to retrieve the neighborhood of a node. Basically, it loads a graph and stores it in a headless `sigma.classes.graph` instance, that you can query to retrieve neighborhoods. | |||||
It is useful for people who want to provide a neighborhoods navigation inside a big graph instead of just displaying it, and without having to deploy an API or the list of every neighborhoods. But please note that this plugin is here as an example of what you can do with the graph model, and do not hesitate to try customizing your navigation through graphs. | |||||
This plugin also adds to the graph model a method called "neighborhood". Check the code for more information. | |||||
Here is how to use it: | |||||
````javascript | |||||
var db = new sigma.plugins.neighborhoods(); | |||||
db.load('path/to/my/graph.json', function() { | |||||
var nodeId = 'anyNodeID'; | |||||
mySigmaInstance | |||||
.read(db.neighborhood(nodeId)) | |||||
.refresh(); | |||||
}); | |||||
```` |
@ -0,0 +1,186 @@ | |||||
/** | |||||
* This plugin provides a method to retrieve the neighborhood of a node. | |||||
* Basically, it loads a graph and stores it in a headless sigma.classes.graph | |||||
* instance, that you can query to retrieve neighborhoods. | |||||
* | |||||
* It is useful for people who want to provide a neighborhoods navigation | |||||
* inside a big graph instead of just displaying it, and without having to | |||||
* deploy an API or the list of every neighborhoods. | |||||
* | |||||
* This plugin also adds to the graph model a method called "neighborhood". | |||||
* Check the code for more information. | |||||
* | |||||
* Here is how to use it: | |||||
* | |||||
* > var db = new sigma.plugins.neighborhoods(); | |||||
* > db.load('path/to/my/graph.json', function() { | |||||
* > var nodeId = 'anyNodeID'; | |||||
* > mySigmaInstance | |||||
* > .read(db.neighborhood(nodeId)) | |||||
* > .refresh(); | |||||
* > }); | |||||
*/ | |||||
(function() { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
/** | |||||
* This method takes the ID of node as argument and returns the graph of the | |||||
* specified node, with every other nodes that are connected to it and every | |||||
* edges that connect two of the previously cited nodes. It uses the built-in | |||||
* indexes from sigma's graph model to search in the graph. | |||||
* | |||||
* @param {string} centerId The ID of the center node. | |||||
* @return {object} The graph, as a simple descriptive object, in | |||||
* the format required by the "read" graph method. | |||||
*/ | |||||
sigma.classes.graph.addMethod( | |||||
'neighborhood', | |||||
function(centerId) { | |||||
var k1, | |||||
k2, | |||||
k3, | |||||
node, | |||||
center, | |||||
// Those two local indexes are here just to avoid duplicates: | |||||
localNodesIndex = {}, | |||||
localEdgesIndex = {}, | |||||
// And here is the resulted graph, empty at the moment: | |||||
graph = { | |||||
nodes: [], | |||||
edges: [] | |||||
}; | |||||
// Check that the exists: | |||||
if (!this.nodes(centerId)) | |||||
return graph; | |||||
// Add center. It has to be cloned to add it the "center" attribute | |||||
// without altering the current graph: | |||||
node = this.nodes(centerId); | |||||
center = {}; | |||||
center.center = true; | |||||
for (k1 in node) | |||||
center[k1] = node[k1]; | |||||
localNodesIndex[centerId] = true; | |||||
graph.nodes.push(center); | |||||
// Add neighbors and edges between the center and the neighbors: | |||||
for (k1 in this.allNeighborsIndex[centerId]) { | |||||
if (!localNodesIndex[k1]) { | |||||
localNodesIndex[k1] = true; | |||||
graph.nodes.push(this.nodesIndex[k1]); | |||||
} | |||||
for (k2 in this.allNeighborsIndex[centerId][k1]) | |||||
if (!localEdgesIndex[k2]) { | |||||
localEdgesIndex[k2] = true; | |||||
graph.edges.push(this.edgesIndex[k2]); | |||||
} | |||||
} | |||||
// Add edges connecting two neighbors: | |||||
for (k1 in localNodesIndex) | |||||
if (k1 !== centerId) | |||||
for (k2 in localNodesIndex) | |||||
if ( | |||||
k2 !== centerId && | |||||
k1 !== k2 && | |||||
this.allNeighborsIndex[k1][k2] | |||||
) | |||||
for (k3 in this.allNeighborsIndex[k1][k2]) | |||||
if (!localEdgesIndex[k3]) { | |||||
localEdgesIndex[k3] = true; | |||||
graph.edges.push(this.edgesIndex[k3]); | |||||
} | |||||
// Finally, let's return the final graph: | |||||
return graph; | |||||
} | |||||
); | |||||
sigma.utils.pkg('sigma.plugins'); | |||||
/** | |||||
* sigma.plugins.neighborhoods constructor. | |||||
*/ | |||||
sigma.plugins.neighborhoods = function() { | |||||
var ready = false, | |||||
readyCallbacks = [], | |||||
graph = new sigma.classes.graph(); | |||||
/** | |||||
* This method just returns the neighborhood of a node. | |||||
* | |||||
* @param {string} centerNodeID The ID of the center node. | |||||
* @return {object} Returns the neighborhood. | |||||
*/ | |||||
this.neighborhood = function(centerNodeID) { | |||||
return graph.neighborhood(centerNodeID); | |||||
}; | |||||
/** | |||||
* This method loads the JSON graph at "path", stores it in the local graph | |||||
* instance, and executes the callback. | |||||
* | |||||
* @param {string} path The path of the JSON graph file. | |||||
* @param {?function} callback Eventually a callback to execute. | |||||
*/ | |||||
this.load = function(path, callback) { | |||||
// Quick XHR polyfill: | |||||
var xhr = (function() { | |||||
if (window.XMLHttpRequest) | |||||
return new XMLHttpRequest(); | |||||
var names, | |||||
i; | |||||
if (window.ActiveXObject) { | |||||
names = [ | |||||
'Msxml2.XMLHTTP.6.0', | |||||
'Msxml2.XMLHTTP.3.0', | |||||
'Msxml2.XMLHTTP', | |||||
'Microsoft.XMLHTTP' | |||||
]; | |||||
for (i in names) | |||||
try { | |||||
return new ActiveXObject(names[i]); | |||||
} catch (e) {} | |||||
} | |||||
return null; | |||||
})(); | |||||
if (!xhr) | |||||
throw 'XMLHttpRequest not supported, cannot load the data.'; | |||||
xhr.open('GET', path, true); | |||||
xhr.onreadystatechange = function() { | |||||
if (xhr.readyState === 4) { | |||||
graph.clear().read(JSON.parse(xhr.responseText)); | |||||
if (callback) | |||||
callback(); | |||||
} | |||||
}; | |||||
// Start loading the file: | |||||
xhr.send(); | |||||
return this; | |||||
}; | |||||
/** | |||||
* This method cleans the graph instance "reads" a graph into it. | |||||
* | |||||
* @param {object} g The graph object to read. | |||||
*/ | |||||
this.read = function(g) { | |||||
graph.clear().read(g); | |||||
}; | |||||
}; | |||||
}).call(window); |
@ -0,0 +1,8 @@ | |||||
sigma.plugins.relativeSize | |||||
===================== | |||||
Plugin developed by [Anatoliy Stegniy](https://github.com/tsdaemon). | |||||
--- | |||||
This plugin provides a method to change nodes size depending to their degree (number of relationships) |
@ -0,0 +1,28 @@ | |||||
(function() { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
sigma.utils.pkg('sigma.plugins'); | |||||
var _id = 0, | |||||
_cache = {}; | |||||
/** | |||||
* This function will change size for all nodes depending to their degree | |||||
* | |||||
* @param {sigma} s The related sigma instance. | |||||
* @param {object} initialSize Start size property | |||||
*/ | |||||
sigma.plugins.relativeSize = function(s, initialSize) { | |||||
var nodes = s.graph.nodes(); | |||||
// second create size for every node | |||||
for(var i = 0; i < nodes.length; i++) { | |||||
var degree = s.graph.degree(nodes[i].id); | |||||
nodes[i].size = initialSize * Math.sqrt(degree); | |||||
} | |||||
s.refresh(); | |||||
}; | |||||
}).call(window); |
@ -0,0 +1,21 @@ | |||||
sigma.renderers.customEdgeShapes | |||||
================== | |||||
Plugin developed by [Sébastien Heymann](https://github.com/sheymann) for [Linkurious](https://github.com/Linkurious). | |||||
Contact: seb@linkurio.us | |||||
--- | |||||
## General | |||||
This plugin registers custom edge shape renderers. See the following [example code](../../examples/plugin-customEdgeShapes.html) for full usage. | |||||
To use, include all .js files under this folder. | |||||
## Shapes | |||||
The plugin implements the following shapes: | |||||
* `dashed` | |||||
* `dotted` | |||||
* `parallel`: two solid parallel lines representing an edge aggregating multiple edges in the original graph. | |||||
* `tapered` (see Danny Holten, Petra Isenberg, Jean-Daniel Fekete, and J. Van Wijk (2010) Performance Evaluation of Tapered, Curved, and Animated Directed-Edge Representations in Node-Link Graphs. Research Report, Sep 2010.) | |||||
To assign a shape renderer to an edge, simply set `edge.type='shape-name'` e.g. `edge.type='dotted'`. The default renderer implemented by sigma.js is named `def` (alias `line`) - see also [generic custom edge renderer example](../../examples/custom-edge-renderer.html). |
@ -0,0 +1,64 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edgehovers'); | |||||
/** | |||||
* This hover renderer will display the edge with a different color or size. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edgehovers.dashed = | |||||
function(edge, source, target, context, settings) { | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
if (settings('edgeHoverColor') === 'edge') { | |||||
color = edge.hover_color || color; | |||||
} else { | |||||
color = edge.hover_color || settings('defaultEdgeHoverColor') || color; | |||||
} | |||||
size *= settings('edgeHoverSizeRatio'); | |||||
context.save(); | |||||
context.setLineDash([8,3]); | |||||
context.strokeStyle = color; | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'] | |||||
); | |||||
context.lineTo( | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'] | |||||
); | |||||
context.stroke(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,64 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edgehovers'); | |||||
/** | |||||
* This hover renderer will display the edge with a different color or size. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edgehovers.dotted = | |||||
function(edge, source, target, context, settings) { | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
if (settings('edgeHoverColor') === 'edge') { | |||||
color = edge.hover_color || color; | |||||
} else { | |||||
color = edge.hover_color || settings('defaultEdgeHoverColor') || color; | |||||
} | |||||
size *= settings('edgeHoverSizeRatio'); | |||||
context.save(); | |||||
context.setLineDash([2]); | |||||
context.strokeStyle = color; | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'] | |||||
); | |||||
context.lineTo( | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'] | |||||
); | |||||
context.stroke(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,77 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edgehovers'); | |||||
/** | |||||
* This hover renderer will display the edge with a different color or size. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edgehovers.parallel = | |||||
function(edge, source, target, context, settings) { | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'), | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y'], | |||||
c, | |||||
d, | |||||
dist = sigma.utils.getDistance(sX, sY, tX, tY); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
if (settings('edgeHoverColor') === 'edge') { | |||||
color = edge.hover_color || color; | |||||
} else { | |||||
color = edge.hover_color || settings('defaultEdgeHoverColor') || color; | |||||
} | |||||
size *= settings('edgeHoverSizeRatio'); | |||||
// Intersection points of the source node circle: | |||||
c = sigma.utils.getCircleIntersection(sX, sY, size, tX, tY, dist); | |||||
// Intersection points of the target node circle: | |||||
d = sigma.utils.getCircleIntersection(tX, tY, size, sX, sY, dist); | |||||
context.save(); | |||||
context.strokeStyle = color; | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo(c.xi, c.yi); | |||||
context.lineTo(d.xi_prime, d.yi_prime); | |||||
context.closePath(); | |||||
context.stroke(); | |||||
context.beginPath(); | |||||
context.moveTo(c.xi_prime, c.yi_prime); | |||||
context.lineTo(d.xi, d.yi); | |||||
context.closePath(); | |||||
context.stroke(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,74 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edgehovers'); | |||||
/** | |||||
* This hover renderer will display the edge with a different color or size. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edgehovers.tapered = | |||||
function(edge, source, target, context, settings) { | |||||
// The goal is to draw a triangle where the target node is a point of | |||||
// the triangle, and the two other points are the intersection of the | |||||
// source circle and the circle (target, distance(source, target)). | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
prefix = settings('prefix') || '', | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'), | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y'], | |||||
dist = sigma.utils.getDistance(sX, sY, tX, tY); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
if (settings('edgeHoverColor') === 'edge') { | |||||
color = edge.hover_color || color; | |||||
} else { | |||||
color = edge.hover_color || settings('defaultEdgeHoverColor') || color; | |||||
} | |||||
size *= settings('edgeHoverSizeRatio'); | |||||
// Intersection points: | |||||
var c = sigma.utils.getCircleIntersection(sX, sY, size, tX, tY, dist); | |||||
context.save(); | |||||
// Turn transparency on: | |||||
context.globalAlpha = 0.65; | |||||
// Draw the triangle: | |||||
context.fillStyle = color; | |||||
context.beginPath(); | |||||
context.moveTo(tX, tY); | |||||
context.lineTo(c.xi, c.yi); | |||||
context.lineTo(c.xi_prime, c.yi_prime); | |||||
context.closePath(); | |||||
context.fill(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,64 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edges'); | |||||
/** | |||||
* This method renders the edge as a dashed line. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.dashed = function(edge, source, target, context, settings) { | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
context.save(); | |||||
if (edge.active) { | |||||
context.strokeStyle = settings('edgeActiveColor') === 'edge' ? | |||||
(color || defaultEdgeColor) : | |||||
settings('defaultEdgeActiveColor'); | |||||
} | |||||
else { | |||||
context.strokeStyle = color; | |||||
} | |||||
context.setLineDash([8,3]); | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'] | |||||
); | |||||
context.lineTo( | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'] | |||||
); | |||||
context.stroke(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,64 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edges'); | |||||
/** | |||||
* This method renders the edge as a dotted line. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.dotted = function(edge, source, target, context, settings) { | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
context.save(); | |||||
if (edge.active) { | |||||
context.strokeStyle = settings('edgeActiveColor') === 'edge' ? | |||||
(color || defaultEdgeColor) : | |||||
settings('defaultEdgeActiveColor'); | |||||
} | |||||
else { | |||||
context.strokeStyle = color; | |||||
} | |||||
context.setLineDash([2]); | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo( | |||||
source[prefix + 'x'], | |||||
source[prefix + 'y'] | |||||
); | |||||
context.lineTo( | |||||
target[prefix + 'x'], | |||||
target[prefix + 'y'] | |||||
); | |||||
context.stroke(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,77 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edges'); | |||||
/** | |||||
* This method renders the edge as two parallel lines. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.parallel = function(edge, source, target, context, settings) { | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'), | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y'], | |||||
c, | |||||
d, | |||||
dist = sigma.utils.getDistance(sX, sY, tX, tY); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
// Intersection points of the source node circle: | |||||
c = sigma.utils.getCircleIntersection(sX, sY, size, tX, tY, dist); | |||||
// Intersection points of the target node circle: | |||||
d = sigma.utils.getCircleIntersection(tX, tY, size, sX, sY, dist); | |||||
context.save(); | |||||
if (edge.active) { | |||||
context.strokeStyle = settings('edgeActiveColor') === 'edge' ? | |||||
(color || defaultEdgeColor) : | |||||
settings('defaultEdgeActiveColor'); | |||||
} | |||||
else { | |||||
context.strokeStyle = color; | |||||
} | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo(c.xi, c.yi); | |||||
context.lineTo(d.xi_prime, d.yi_prime); | |||||
context.closePath(); | |||||
context.stroke(); | |||||
context.beginPath(); | |||||
context.moveTo(c.xi_prime, c.yi_prime); | |||||
context.lineTo(d.xi, d.yi); | |||||
context.closePath(); | |||||
context.stroke(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,77 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edges'); | |||||
/** | |||||
* This method renders the edge as a tapered line. | |||||
* Danny Holten, Petra Isenberg, Jean-Daniel Fekete, and J. Van Wijk (2010) | |||||
* Performance Evaluation of Tapered, Curved, and Animated Directed-Edge | |||||
* Representations in Node-Link Graphs. Research Report, Sep 2010. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.tapered = function(edge, source, target, context, settings) { | |||||
// The goal is to draw a triangle where the target node is a point of | |||||
// the triangle, and the two other points are the intersection of the | |||||
// source circle and the circle (target, distance(source, target)). | |||||
var color = edge.active ? | |||||
edge.active_color || settings('defaultEdgeActiveColor') : | |||||
edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
prefix = settings('prefix') || '', | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'), | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y'], | |||||
dist = sigma.utils.getDistance(sX, sY, tX, tY); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
// Intersection points: | |||||
var c = sigma.utils.getCircleIntersection(sX, sY, size, tX, tY, dist); | |||||
context.save(); | |||||
if (edge.active) { | |||||
context.fillStyle = settings('edgeActiveColor') === 'edge' ? | |||||
(color || defaultEdgeColor) : | |||||
settings('defaultEdgeActiveColor'); | |||||
} | |||||
else { | |||||
context.fillStyle = color; | |||||
} | |||||
// Turn transparency on: | |||||
context.globalAlpha = 0.65; | |||||
// Draw the triangle: | |||||
context.beginPath(); | |||||
context.moveTo(tX, tY); | |||||
context.lineTo(c.xi, c.yi); | |||||
context.lineTo(c.xi_prime, c.yi_prime); | |||||
context.closePath(); | |||||
context.fill(); | |||||
context.restore(); | |||||
}; | |||||
})(); |
@ -0,0 +1,61 @@ | |||||
sigma.renderers.customShapes | |||||
================== | |||||
Plugin developed by [Ron Peleg](https://github.com/rpeleg1970). | |||||
--- | |||||
## General | |||||
This plugin registers custom node shape renderers, and allows adding scaled images on top of them. See the following [example code](../../examples/plugin-customShapes.html) for full usage. | |||||
To use, include all .js files under this folder. | |||||
The plugin implements the `node.borderColor` property to allow control of the (surprise) border color. | |||||
## Shapes | |||||
The plugin implements the following shapes. To set a shape renderer, you simply set `node.type='shape-name'` e.g. `node.type='star'`. The default renderer implemented by sigma.js is named `def` - see also [generic custom node renderer example](../../examples/custom-node-renderer.html) | |||||
* `circle`: similar to the `def` renderer, but also allows images | |||||
* `square` | |||||
* `diamond` | |||||
* `equilateral`: equilateral polygon. you can control additional properties in this polygon by setting more values as follows: | |||||
````javascript | |||||
node.equilateral = { | |||||
rotate: /* rotate right, value in deg */, | |||||
numPoints: /* default 5, integer */ | |||||
} | |||||
```` | |||||
* `star`: you can control additional properties in this star by setting more as follows: | |||||
````javascript | |||||
node.star = { | |||||
numPoints: /* default 5, integer */, | |||||
innerRatio: /* ratio of inner radius in star, compared to node.size */ | |||||
} | |||||
```` | |||||
* `cross`: plus shape. you can control additional properties in this polygon by setting more values as follows: | |||||
````javascript | |||||
node.cross = { | |||||
lineWeight: /* width of cross arms */, | |||||
} | |||||
```` | |||||
* `pacman`: an example of a more exotic renderer | |||||
The list of available renderer types can be obtained by calling `ShapeLibrary.enumerate()` | |||||
## Images | |||||
You can add an image to any node, simply by adding `node.image` property, with the following content: | |||||
````javascript | |||||
node.image = { | |||||
url: /* mandatory image URL */, | |||||
clip: /* Ratio of image clipping disk compared to node size (def 1.0) - see example to how we adapt this to differenmt shapes */, | |||||
scale: /* Ratio of how to scale the image, compared to node size, default 1.0 */, | |||||
w: /* numeric width - important for correct scaling if w/h ratio is not 1.0 */, | |||||
h: /* numeric height - important for correct scaling if w/h ratio is not 1.0 */ | |||||
} | |||||
```` | |||||
Because the plug-in calls the sigma instance `refresh()` method on image loading, you MUST init as follows or you will not see rendered images: | |||||
````javascript | |||||
s = new sigma({ | |||||
... | |||||
}); | |||||
CustomShapes.init(s); | |||||
s.refresh(); | |||||
```` |
@ -0,0 +1,162 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
var shapes = []; | |||||
var register = function(name,drawShape,drawBorder) { | |||||
shapes.push({ | |||||
'name': name, | |||||
'drawShape': drawShape, | |||||
'drawBorder': drawBorder | |||||
}); | |||||
} | |||||
var enumerateShapes = function() { | |||||
return shapes; | |||||
} | |||||
/** | |||||
* For the standard closed shapes - the shape fill and border are drawn the | |||||
* same, with some minor differences for fill and border. To facilitate this we | |||||
* create the generic draw functions, that take a shape drawing func and | |||||
* return a shape-renderer/border-renderer | |||||
* ---------- | |||||
*/ | |||||
var genericDrawShape = function(shapeFunc) { | |||||
return function(node,x,y,size,color,context) { | |||||
context.fillStyle = color; | |||||
context.beginPath(); | |||||
shapeFunc(node,x,y,size,context); | |||||
context.closePath(); | |||||
context.fill(); | |||||
}; | |||||
} | |||||
var genericDrawBorder = function(shapeFunc) { | |||||
return function(node,x,y,size,color,context) { | |||||
context.strokeStyle = color; | |||||
context.lineWidth = size / 5; | |||||
context.beginPath(); | |||||
shapeFunc(node,x,y,size,context); | |||||
context.closePath(); | |||||
context.stroke(); | |||||
}; | |||||
} | |||||
/** | |||||
* We now proced to use the generics to define our standard shape/border | |||||
* drawers: square, diamond, equilateral (polygon), and star | |||||
* ---------- | |||||
*/ | |||||
var drawSquare = function(node,x,y,size,context) { | |||||
var rotate = Math.PI*45/180; // 45 deg rotation of a diamond shape | |||||
context.moveTo(x+size*Math.sin(rotate), y-size*Math.cos(rotate)); // first point on outer radius, dwangle 'rotate' | |||||
for(var i=1; i<4; i++) { | |||||
context.lineTo(x+Math.sin(rotate+2*Math.PI*i/4)*size, y-Math.cos(rotate+2*Math.PI*i/4)*size); | |||||
} | |||||
} | |||||
register("square",genericDrawShape(drawSquare),genericDrawBorder(drawSquare)); | |||||
var drawCircle = function(node,x,y,size,context) { | |||||
context.arc(x,y,size,0,Math.PI*2,true); | |||||
} | |||||
register("circle",genericDrawShape(drawCircle),genericDrawBorder(drawCircle)); | |||||
var drawDiamond = function(node,x,y,size,context) { | |||||
context.moveTo(x-size, y); | |||||
context.lineTo(x, y-size); | |||||
context.lineTo(x+size, y); | |||||
context.lineTo(x, y+size); | |||||
} | |||||
register("diamond",genericDrawShape(drawDiamond),genericDrawBorder(drawDiamond)); | |||||
var drawCross = function(node,x,y,size,context) { | |||||
var lineWeight = (node.cross && node.cross.lineWeight) || 5; | |||||
context.moveTo(x-size, y-lineWeight); | |||||
context.lineTo(x-size, y+lineWeight); | |||||
context.lineTo(x-lineWeight, y+lineWeight); | |||||
context.lineTo(x-lineWeight, y+size); | |||||
context.lineTo(x+lineWeight, y+size); | |||||
context.lineTo(x+lineWeight, y+lineWeight); | |||||
context.lineTo(x+size, y+lineWeight); | |||||
context.lineTo(x+size, y-lineWeight); | |||||
context.lineTo(x+lineWeight, y-lineWeight); | |||||
context.lineTo(x+lineWeight, y-size); | |||||
context.lineTo(x-lineWeight, y-size); | |||||
context.lineTo(x-lineWeight, y-lineWeight); | |||||
} | |||||
register("cross",genericDrawShape(drawCross),genericDrawBorder(drawCross)); | |||||
var drawEquilateral = function(node,x,y,size,context) { | |||||
var pcount = (node.equilateral && node.equilateral.numPoints) || 5; | |||||
var rotate = ((node.equilateral && node.equilateral.rotate) || 0)*Math.PI/180; | |||||
var radius = size; | |||||
context.moveTo(x+radius*Math.sin(rotate), y-radius*Math.cos(rotate)); // first point on outer radius, angle 'rotate' | |||||
for(var i=1; i<pcount; i++) { | |||||
context.lineTo(x+Math.sin(rotate+2*Math.PI*i/pcount)*radius, y-Math.cos(rotate+2*Math.PI*i/pcount)*radius); | |||||
} | |||||
} | |||||
register("equilateral",genericDrawShape(drawEquilateral),genericDrawBorder(drawEquilateral)); | |||||
var starShape = function(node,x,y,size,context) { | |||||
var pcount = (node.star && node.star.numPoints) || 5, | |||||
inRatio = (node.star && node.star.innerRatio) || 0.5, | |||||
outR = size, | |||||
inR = size*inRatio, | |||||
angleOffset = Math.PI/pcount; | |||||
context.moveTo(x, y-size); // first point on outer radius, top | |||||
for(var i=0; i<pcount; i++) { | |||||
context.lineTo(x+Math.sin(angleOffset+2*Math.PI*i/pcount)*inR, | |||||
y-Math.cos(angleOffset+2*Math.PI*i/pcount)*inR); | |||||
context.lineTo(x+Math.sin(2*Math.PI*(i+1)/pcount)*outR, | |||||
y-Math.cos(2*Math.PI*(i+1)/pcount)*outR); | |||||
} | |||||
} | |||||
register("star",genericDrawShape(starShape),genericDrawBorder(starShape)); | |||||
/** | |||||
* An example of a non standard shape (pacman). Here we WILL NOT use the | |||||
* genericDraw functions, but rather register a full custom node renderer for | |||||
* fill, and skip the border renderer which is irrelevant for this shape | |||||
* ---------- | |||||
*/ | |||||
var drawPacman = function(node,x,y,size,color,context) { | |||||
context.fillStyle = 'yellow'; | |||||
context.beginPath(); | |||||
context.arc(x,y,size,1.25*Math.PI,0,false); | |||||
context.arc(x,y,size,0,0.75*Math.PI,false); | |||||
context.lineTo(x,y); | |||||
context.closePath(); | |||||
context.fill(); | |||||
context.fillStyle = 'white'; | |||||
context.strokeStyle = 'black'; | |||||
context.beginPath(); | |||||
context.arc(x+size/3,y-size/3,size/4,0,2*Math.PI,false); | |||||
context.closePath(); | |||||
context.fill(); | |||||
context.stroke(); | |||||
context.fillStyle = 'black'; | |||||
context.beginPath(); | |||||
context.arc(x+4*size/9,y-size/3,size/8,0,2*Math.PI,false); | |||||
context.closePath(); | |||||
context.fill(); | |||||
} | |||||
register("pacman",drawPacman,null); | |||||
/** | |||||
* Exporting | |||||
* ---------- | |||||
*/ | |||||
this.ShapeLibrary = { | |||||
// Functions | |||||
enumerate: enumerateShapes, | |||||
// add: addShape, | |||||
// Version | |||||
version: '0.1' | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,236 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
if (typeof ShapeLibrary === 'undefined') | |||||
throw 'ShapeLibrary is not declared'; | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.canvas.nodes'); | |||||
sigma.utils.pkg('sigma.svg.nodes'); | |||||
var sigInst = undefined; | |||||
var imgCache = {}; | |||||
var initPlugin = function(inst) { | |||||
sigInst = inst; | |||||
} | |||||
var drawImage = function (node,x,y,size,context) { | |||||
if(sigInst && node.image && node.image.url) { | |||||
var url = node.image.url; | |||||
var ih = node.image.h || 1; // 1 is arbitrary, anyway only the ratio counts | |||||
var iw = node.image.w || 1; | |||||
var scale = node.image.scale || 1; | |||||
var clip = node.image.clip || 1; | |||||
// create new IMG or get from imgCache | |||||
var image = imgCache[url]; | |||||
if(!image) { | |||||
image = document.createElement('IMG'); | |||||
image.src = url; | |||||
image.status = 'loading'; | |||||
image.onerror = function() { | |||||
console.log("error loading", url); | |||||
image.status = 'error'; | |||||
}; | |||||
image.onload = function(){ | |||||
// TODO see how we redraw on load | |||||
// need to provide the siginst as a parameter to the library | |||||
console.log("redraw on image load", url); | |||||
image.status = 'ok'; | |||||
sigInst.refresh(); | |||||
}; | |||||
imgCache[url] = image; | |||||
} | |||||
// calculate position and draw | |||||
var xratio = (iw<ih) ? (iw/ih) : 1; | |||||
var yratio = (ih<iw) ? (ih/iw) : 1; | |||||
var r = size*scale; | |||||
// Draw the clipping disc: | |||||
context.save(); // enter clipping mode | |||||
context.beginPath(); | |||||
context.arc(x,y,size*clip,0,Math.PI*2,true); | |||||
context.closePath(); | |||||
context.clip(); | |||||
if(image.status === 'ok') { | |||||
// Draw the actual image | |||||
context.drawImage(image, | |||||
x+Math.sin(-3.142/4)*r*xratio, | |||||
y-Math.cos(-3.142/4)*r*yratio, | |||||
r*xratio*2*Math.sin(-3.142/4)*(-1), | |||||
r*yratio*2*Math.cos(-3.142/4)); | |||||
} | |||||
context.restore(); // exit clipping mode | |||||
} | |||||
} | |||||
var drawSVGImage = function (node, group, settings) { | |||||
if(sigInst && node.image && node.image.url) { | |||||
var clipCircle = document.createElementNS(settings('xmlns'), 'circle'), | |||||
clipPath = document.createElementNS(settings('xmlns'), 'clipPath'), | |||||
clipPathId = settings('classPrefix') + '-clip-path-' + node.id, | |||||
def = document.createElementNS(settings('xmlns'), 'defs'), | |||||
image = document.createElementNS(settings('xmlns'), 'image'), | |||||
url = node.image.url; | |||||
clipPath.setAttributeNS(null, 'id', clipPathId); | |||||
clipPath.appendChild(clipCircle); | |||||
def.appendChild(clipPath); | |||||
// angular's base tag will change the relative fragment id, so | |||||
// #<clipPathId> doesn't work | |||||
// HACKHACK: IE <=9 does not respect the HTML base element in SVG. | |||||
// They don't need the current URL in the clip path reference. | |||||
var absolutePath = /MSIE [5-9]/.test(navigator.userAgent) ? | |||||
"" : document.location.href; | |||||
// To fix cases where an anchor tag was used | |||||
absolutePath = absolutePath.split("#")[0]; | |||||
image.setAttributeNS(null, 'class', | |||||
settings('classPrefix') + '-node-image'); | |||||
image.setAttributeNS(null, 'clip-path', | |||||
'url(' + absolutePath + '#' + clipPathId + ')'); | |||||
image.setAttributeNS(null, 'pointer-events', 'none'); | |||||
image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', | |||||
node.image.url); | |||||
group.appendChild(def); | |||||
group.appendChild(image); | |||||
} | |||||
} | |||||
var register = function(name,drawShape,drawBorder) { | |||||
sigma.canvas.nodes[name] = function(node, context, settings) { | |||||
var args = arguments, | |||||
prefix = settings('prefix') || '', | |||||
size = node[prefix + 'size'], | |||||
color = node.color || settings('defaultNodeColor'), | |||||
borderColor = node.borderColor || color, | |||||
x = node[prefix + 'x'], | |||||
y = node[prefix + 'y']; | |||||
context.save(); | |||||
if(drawShape) { | |||||
drawShape(node,x,y,size,color,context); | |||||
} | |||||
if(drawBorder) { | |||||
drawBorder(node,x,y,size,borderColor,context); | |||||
} | |||||
drawImage(node,x,y,size,context); | |||||
context.restore(); | |||||
}; | |||||
sigma.svg.nodes[name] = { | |||||
create: function(node, settings) { | |||||
var group = document.createElementNS(settings('xmlns'), 'g'), | |||||
circle = document.createElementNS(settings('xmlns'), 'circle'); | |||||
group.setAttributeNS(null, 'class', | |||||
settings('classPrefix') + '-node-group'); | |||||
group.setAttributeNS(null, 'data-node-id', node.id); | |||||
// Defining the node's circle | |||||
circle.setAttributeNS(null, 'data-node-id', node.id); | |||||
circle.setAttributeNS(null, 'class', | |||||
settings('classPrefix') + '-node'); | |||||
circle.setAttributeNS(null, 'fill', | |||||
node.color || settings('defaultNodeColor')); | |||||
group.appendChild(circle); | |||||
drawSVGImage(node, group, settings); | |||||
return group; | |||||
}, | |||||
update: function(node, group, settings) { | |||||
var classPrefix = settings('classPrefix'), | |||||
clip = node.image.clip || 1, | |||||
// 1 is arbitrary, anyway only the ratio counts | |||||
ih = node.image.h || 1, | |||||
iw = node.image.w || 1, | |||||
prefix = settings('prefix') || '', | |||||
scale = node.image.scale || 1, | |||||
size = node[prefix + 'size'], | |||||
x = node[prefix + 'x'], | |||||
y = node[prefix + 'y']; | |||||
var r = scale * size, | |||||
xratio = (iw<ih) ? (iw/ih) : 1, | |||||
yratio = (ih<iw) ? (ih/iw) : 1; | |||||
for(var i = 0, childNodes = group.childNodes; i < childNodes.length; i ++) { | |||||
var className = childNodes[i].getAttribute('class'); | |||||
switch (className) { | |||||
case classPrefix + '-node': | |||||
childNodes[i].setAttributeNS(null, 'cx', x); | |||||
childNodes[i].setAttributeNS(null, 'cy', y); | |||||
childNodes[i].setAttributeNS(null, 'r', size); | |||||
// // Updating only if not freestyle | |||||
if (!settings('freeStyle')) { | |||||
childNodes[i].setAttributeNS( | |||||
null, | |||||
'fill', | |||||
node.color || settings('defaultNodeColor')); | |||||
} | |||||
break; | |||||
case classPrefix + '-node-image': | |||||
childNodes[i].setAttributeNS(null, 'x', | |||||
x+Math.sin(-3.142/4)*r*xratio); | |||||
childNodes[i].setAttributeNS(null, 'y', | |||||
y-Math.cos(-3.142/4)*r*yratio); | |||||
childNodes[i].setAttributeNS(null, 'width', | |||||
r*xratio*2*Math.sin(-3.142/4)*(-1)); | |||||
childNodes[i].setAttributeNS(null, 'height', | |||||
r*yratio*2*Math.cos(-3.142/4)); | |||||
break; | |||||
default: | |||||
// no class name, must be the clip-path | |||||
var clipPath = childNodes[i].firstChild; | |||||
if (clipPath != null) { | |||||
var clipPathId = classPrefix + '-clip-path-' + node.id; | |||||
if (clipPath.getAttribute('id') === clipPathId) { | |||||
clipPath.firstChild.setAttributeNS(null, 'cx', x); | |||||
clipPath.firstChild.setAttributeNS(null, 'cy', y); | |||||
clipPath.firstChild.setAttributeNS(null, 'r', | |||||
clip * size); | |||||
} | |||||
} | |||||
break; | |||||
} | |||||
} | |||||
// showing | |||||
group.style.display = ''; | |||||
} | |||||
} | |||||
} | |||||
ShapeLibrary.enumerate().forEach(function(shape) { | |||||
register(shape.name,shape.drawShape,shape.drawBorder); | |||||
}); | |||||
/** | |||||
* Exporting | |||||
* ---------- | |||||
*/ | |||||
this.CustomShapes = { | |||||
// Functions | |||||
init: initPlugin, | |||||
// add pre-cache images | |||||
// Version | |||||
version: '0.1' | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,38 @@ | |||||
sigma.renderers.edgeDots | |||||
======================== | |||||
Plugin developed by [Joakim af Sandeberg](https://github.com/jotunacorn). | |||||
Contact: joakim.afs+github@gmail.com | |||||
--- | |||||
## General | |||||
This plugin adds the option to show colored dots near the source and target of an edge when using the canvas renderer. | |||||
See the following [example](../../examples/plugin-edgeDots.html) for full usage. | |||||
To use it, include all .js files under this folder. | |||||
## Edges | |||||
This plugin extends Sigma.js canvas edges: | |||||
* **sourceDotColor** | |||||
* The value to use as color for the source dot. If left undefined there will be no dot at the source. | |||||
* type: *string* | |||||
* default value: undefined | |||||
* **targetDotColor** | |||||
* The value to use as color for the target dot. If left undefined there will be no dot at the target. | |||||
* type: *string* | |||||
* default value: undefined | |||||
* **dotOffset** | |||||
* The value which define the distance between the dots and the nodes, relative to the node size. | |||||
* type: *number* | |||||
* default value: 3 | |||||
* **dotSize** | |||||
* The value which define the size of the dot relative to the edge. | |||||
* type: *number* | |||||
* default value: 1 | |||||
## Renderers | |||||
This plugin modifies the sigma.canvas.edges.curve and sigma.canvas.edges.curvedArrow | |||||
@ -0,0 +1,114 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edges'); | |||||
/** | |||||
* This edge renderer will display edges as curves. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.dotCurve = function(edge, source, target, context, settings) { | |||||
var color = edge.color, | |||||
prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1, | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'), | |||||
cp = {}, | |||||
sSize = source[prefix + 'size'], | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y']; | |||||
cp = (source.id === target.id) ? | |||||
sigma.utils.getSelfLoopControlPoints(sX, sY, sSize) : | |||||
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
context.strokeStyle = color; | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo(sX, sY); | |||||
if (source.id === target.id) { | |||||
context.bezierCurveTo(cp.x1, cp.y1, cp.x2, cp.y2, tX, tY); | |||||
} else { | |||||
context.quadraticCurveTo(cp.x, cp.y, tX, tY); | |||||
} | |||||
context.stroke(); | |||||
if(edge.sourceDotColor != undefined || edge.targetDotColor != undefined) { | |||||
var dotOffset = edge.dotOffset || 3; | |||||
var dotSize = edge.dotSize || 1; | |||||
dotSize = size*dotSize; | |||||
dotOffset = dotOffset*sSize; | |||||
if(edge.sourceDotColor != undefined) { | |||||
createDot(context, sX, sY, cp, tX, tY, dotOffset, dotSize, edge.sourceDotColor); | |||||
} | |||||
if (edge.targetDotColor != undefined){ | |||||
createDot(context, tX, tY, cp, sX, sY, dotOffset, dotSize, edge.targetDotColor); | |||||
} | |||||
} | |||||
}; | |||||
function createDot(context, sX, sY, cp, tX, tY, offset, size, color) { | |||||
context.beginPath(); | |||||
context.fillStyle = color; | |||||
var dot = getPointOnBezier(sX, sY, cp.x, cp.y, tX, tY, | |||||
offset); | |||||
context.arc(dot.x, dot.y, size * 3, 0, 2 * Math.PI, | |||||
false); | |||||
context.fill(); | |||||
} | |||||
function getQBezierValue(t, p1, p2, p3) { | |||||
var iT = 1 - t; | |||||
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3; | |||||
} | |||||
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) { | |||||
return { | |||||
x:getQBezierValue(position, startX, cpX, endX), | |||||
y:getQBezierValue(position, startY, cpY, endY) | |||||
}; | |||||
} | |||||
function getDistanceBetweenPoints(x1, y1, x2, y2){ | |||||
return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); | |||||
} | |||||
/* Function to get a point on a bezier curve a certain distance away from | |||||
its source. Needed since the position on a beziercurve is given to the | |||||
formula as a percentage (t).*/ | |||||
function getPointOnBezier(startX, startY, cpX, cpY, endX, endY, distance){ | |||||
var bestT = 0; | |||||
var bestAccuracy = 1000; | |||||
var stepSize = 0.001; | |||||
for(var t = 0; t<1; t+=stepSize){ | |||||
var currentPoint = getQuadraticCurvePoint(startX, startY, cpX, cpY, | |||||
endX, endY, t); | |||||
var currentDistance = getDistanceBetweenPoints(startX, startY, | |||||
currentPoint.x, currentPoint.y); | |||||
if(Math.abs(currentDistance-distance) < bestAccuracy){ | |||||
bestAccuracy = Math.abs(currentDistance-distance); | |||||
bestT = t; | |||||
} | |||||
} | |||||
return getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, bestT); | |||||
} | |||||
})(); |
@ -0,0 +1,145 @@ | |||||
;(function() { | |||||
'use strict'; | |||||
sigma.utils.pkg('sigma.canvas.edges'); | |||||
/** | |||||
* This edge renderer will display edges as curves with arrow heading. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.dotCurvedArrow = | |||||
function(edge, source, target, context, settings) { | |||||
var color = edge.color, | |||||
prefix = settings('prefix') || '', | |||||
edgeColor = settings('edgeColor'), | |||||
defaultNodeColor = settings('defaultNodeColor'), | |||||
defaultEdgeColor = settings('defaultEdgeColor'), | |||||
cp = {}, | |||||
size = edge[prefix + 'size'] || 1, | |||||
count = edge.count || 0, | |||||
tSize = target[prefix + 'size'], | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y'], | |||||
aSize = Math.max(size * 2.5, settings('minArrowSize')), | |||||
d, | |||||
aX, | |||||
aY, | |||||
vX, | |||||
vY; | |||||
cp = (source.id === target.id) ? | |||||
sigma.utils.getSelfLoopControlPoints(sX, sY, tSize, count) : | |||||
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY, count); | |||||
if (source.id === target.id) { | |||||
d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2)); | |||||
aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d; | |||||
aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d; | |||||
vX = (tX - cp.x1) * aSize / d; | |||||
vY = (tY - cp.y1) * aSize / d; | |||||
} | |||||
else { | |||||
d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2)); | |||||
aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d; | |||||
aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d; | |||||
vX = (tX - cp.x) * aSize / d; | |||||
vY = (tY - cp.y) * aSize / d; | |||||
} | |||||
if (!color) | |||||
switch (edgeColor) { | |||||
case 'source': | |||||
color = source.color || defaultNodeColor; | |||||
break; | |||||
case 'target': | |||||
color = target.color || defaultNodeColor; | |||||
break; | |||||
default: | |||||
color = defaultEdgeColor; | |||||
break; | |||||
} | |||||
context.strokeStyle = color; | |||||
context.lineWidth = size; | |||||
context.beginPath(); | |||||
context.moveTo(sX, sY); | |||||
if (source.id === target.id) { | |||||
context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY); | |||||
} else { | |||||
context.quadraticCurveTo(cp.x, cp.y, aX, aY); | |||||
} | |||||
context.stroke(); | |||||
context.fillStyle = color; | |||||
context.beginPath(); | |||||
context.moveTo(aX + vX, aY + vY); | |||||
context.lineTo(aX + vY * 0.6, aY - vX * 0.6); | |||||
context.lineTo(aX - vY * 0.6, aY + vX * 0.6); | |||||
context.lineTo(aX + vX, aY + vY); | |||||
context.closePath(); | |||||
context.fill(); | |||||
if(edge.sourceDotColor != undefined || edge.targetDotColor != undefined) { | |||||
var dotOffset = edge.dotOffset || 3; | |||||
var dotSize = edge.dotSize || 1; | |||||
dotSize = size*dotSize; | |||||
dotOffset = dotOffset*tSize; | |||||
if(edge.sourceDotColor != undefined) { | |||||
createDot(context, sX, sY, cp, tX, tY, dotOffset, dotSize, edge.sourceDotColor); | |||||
} | |||||
if (edge.targetDotColor != undefined){ | |||||
createDot(context, tX, tY, cp, sX, sY, dotOffset, dotSize, edge.targetDotColor); | |||||
} | |||||
} | |||||
}; | |||||
function createDot(context, sX, sY, cp, tX, tY, offset, size, color) { | |||||
context.beginPath(); | |||||
context.fillStyle = color; | |||||
var dot = getPointOnBezier(sX, sY, cp.x, cp.y, tX, tY, | |||||
offset); | |||||
context.arc(dot.x, dot.y, size * 3, 0, 2 * Math.PI, | |||||
false); | |||||
context.fill(); | |||||
} | |||||
function getQBezierValue(t, p1, p2, p3) { | |||||
var iT = 1 - t; | |||||
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3; | |||||
} | |||||
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) { | |||||
return { | |||||
x:getQBezierValue(position, startX, cpX, endX), | |||||
y:getQBezierValue(position, startY, cpY, endY) | |||||
}; | |||||
} | |||||
function getDistanceBetweenPoints(x1, y1, x2, y2){ | |||||
return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); | |||||
} | |||||
/* Function to get a point on a bezier curve a certain distance away from | |||||
its source. Needed since the position on a beziercurve is given to the | |||||
formula as a percentage (t).*/ | |||||
function getPointOnBezier(startX, startY, cpX, cpY, endX, endY, distance){ | |||||
var bestT = 0; | |||||
var bestAccuracy = 1000; | |||||
var stepSize = 0.001; | |||||
for(var t = 0; t<1; t+=stepSize){ | |||||
var currentPoint = getQuadraticCurvePoint(startX, startY, cpX, cpY, | |||||
endX, endY, t); | |||||
var currentDistance = getDistanceBetweenPoints(startX, startY, | |||||
currentPoint.x, currentPoint.y); | |||||
if(Math.abs(currentDistance-distance) < bestAccuracy){ | |||||
bestAccuracy = Math.abs(currentDistance-distance); | |||||
bestT = t; | |||||
} | |||||
} | |||||
return getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, bestT); | |||||
} | |||||
})(); |
@ -0,0 +1,76 @@ | |||||
sigma.renderers.edgeLabels | |||||
================== | |||||
Plugin developed by [Sébastien Heymann](https://github.com/sheymann) for [Linkurious](https://github.com/Linkurious). | |||||
Contact: seb@linkurio.us | |||||
--- | |||||
## General | |||||
This plugin displays edge labels. | |||||
See the following [example](../../examples/edge-renderers.html) for full usage. | |||||
To use it, include all .js files under this folder. | |||||
## Settings | |||||
This plugin extends Sigma.js settings in a transparent way to render edge labels, see [settings.js](settings.js): | |||||
* **defaultEdgeLabelColor** | |||||
* type: *string* | |||||
* default value: `#000` | |||||
* **defaultEdgeLabelActiveColor** | |||||
* type: *string* | |||||
* default value: `rgb(236, 81, 72)` | |||||
* **defaultEdgeLabelSize** | |||||
* type: *number* | |||||
* default value: `10` | |||||
* **edgeLabelSize** | |||||
* Indicates how to choose the edge labels size. | |||||
* type: *string* | |||||
* default value: `fixed` | |||||
* available values: `fixed`, `proportional` | |||||
* **edgeLabelSizePowRatio** | |||||
* The opposite power ratio between the font size of the label and the edge size. | |||||
* type: *number* | |||||
* default value: `0.8` | |||||
````javascript | |||||
// Formula: | |||||
Math.pow(size, - 1 / edgeLabelSizePowRatio) * size * defaultEdgeLabelSize | |||||
```` | |||||
* **edgeLabelThreshold** | |||||
* The minimum size an edge must have to see its label displayed. | |||||
* type: *number* | |||||
* default value: `1` | |||||
The plugin also forces `drawEdgeLabels` to `true`. | |||||
The default values provided by the plugin may be overridden when instantiating Sigma, e.g.: | |||||
````javascript | |||||
var sigInst = new sigma({ | |||||
container: 'graph-container', | |||||
settings: { | |||||
edgeLabelSize: 'proportional' | |||||
} | |||||
}); | |||||
```` | |||||
## Renderers | |||||
This plugin provides the following edge label renderers: | |||||
- `line` (default) | |||||
- `arrow` (use default) | |||||
- `curve` | |||||
- `curvedArrow` | |||||
## Compatibility | |||||
This plugin is compatible with `sigma.plugins.activeState`. |
@ -0,0 +1,41 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize package: | |||||
sigma.utils.pkg('sigma.settings'); | |||||
/** | |||||
* Extended sigma settings for sigma.renderers.edgeLabels. | |||||
*/ | |||||
var settings = { | |||||
/** | |||||
* RENDERERS SETTINGS: | |||||
* ******************* | |||||
*/ | |||||
// {string} | |||||
defaultEdgeLabelColor: '#000', | |||||
// {string} | |||||
defaultEdgeLabelActiveColor: '#000', | |||||
// {string} | |||||
defaultEdgeLabelSize: 10, | |||||
// {string} Indicates how to choose the edge labels size. Available values: | |||||
// "fixed", "proportional" | |||||
edgeLabelSize: 'fixed', | |||||
// {string} The opposite power ratio between the font size of the label and | |||||
// the edge size: | |||||
// Math.pow(size, -1 / edgeLabelSizePowRatio) * size * defaultEdgeLabelSize | |||||
edgeLabelSizePowRatio: 1, | |||||
// {number} The minimum size an edge must have to see its label displayed. | |||||
edgeLabelThreshold: 1, | |||||
}; | |||||
// Export the previously designed settings: | |||||
sigma.settings = sigma.utils.extend(sigma.settings || {}, settings); | |||||
// Override default settings: | |||||
sigma.settings.drawEdgeLabels = true; | |||||
}).call(this); |
@ -0,0 +1,112 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.canvas.edges.labels'); | |||||
/** | |||||
* This label renderer will just display the label on the curve of the edge. | |||||
* The label is rendered at half distance of the edge extremities, and is | |||||
* always oriented from left to right on the top side of the curve. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.labels.curve = | |||||
function(edge, source, target, context, settings) { | |||||
if (typeof edge.label !== 'string') | |||||
return; | |||||
var prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1; | |||||
if (size < settings('edgeLabelThreshold')) | |||||
return; | |||||
var fontSize, | |||||
sSize = source[prefix + 'size'], | |||||
sX = source[prefix + 'x'], | |||||
sY = source[prefix + 'y'], | |||||
tX = target[prefix + 'x'], | |||||
tY = target[prefix + 'y'], | |||||
dX = tX - sX, | |||||
dY = tY - sY, | |||||
sign = (sX < tX) ? 1 : -1, | |||||
cp = {}, | |||||
c, | |||||
angle, | |||||
t = 0.5; //length of the curve | |||||
if (source.id === target.id) { | |||||
cp = sigma.utils.getSelfLoopControlPoints(sX, sY, sSize); | |||||
c = sigma.utils.getPointOnBezierCurve( | |||||
t, sX, sY, tX, tY, cp.x1, cp.y1, cp.x2, cp.y2 | |||||
); | |||||
angle = Math.atan2(1, 1); // 45° | |||||
} else { | |||||
cp = sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); | |||||
c = sigma.utils.getPointOnQuadraticCurve(t, sX, sY, tX, tY, cp.x, cp.y); | |||||
angle = Math.atan2(dY * sign, dX * sign); | |||||
} | |||||
// The font size is sublineraly proportional to the edge size, in order to | |||||
// avoid very large labels on screen. | |||||
// This is achieved by f(x) = x * x^(-1/ a), where 'x' is the size and 'a' | |||||
// is the edgeLabelSizePowRatio. Notice that f(1) = 1. | |||||
// The final form is: | |||||
// f'(x) = b * x * x^(-1 / a), thus f'(1) = b. Application: | |||||
// fontSize = defaultEdgeLabelSize if edgeLabelSizePowRatio = 1 | |||||
fontSize = (settings('edgeLabelSize') === 'fixed') ? | |||||
settings('defaultEdgeLabelSize') : | |||||
settings('defaultEdgeLabelSize') * | |||||
size * | |||||
Math.pow(size, -1 / settings('edgeLabelSizePowRatio')); | |||||
context.save(); | |||||
if (edge.active) { | |||||
context.font = [ | |||||
settings('activeFontStyle'), | |||||
fontSize + 'px', | |||||
settings('activeFont') || settings('font') | |||||
].join(' '); | |||||
context.fillStyle = | |||||
settings('edgeActiveColor') === 'edge' ? | |||||
(edge.active_color || settings('defaultEdgeActiveColor')) : | |||||
settings('defaultEdgeLabelActiveColor'); | |||||
} | |||||
else { | |||||
context.font = [ | |||||
settings('fontStyle'), | |||||
fontSize + 'px', | |||||
settings('font') | |||||
].join(' '); | |||||
context.fillStyle = | |||||
(settings('edgeLabelColor') === 'edge') ? | |||||
(edge.color || settings('defaultEdgeColor')) : | |||||
settings('defaultEdgeLabelColor'); | |||||
} | |||||
context.textAlign = 'center'; | |||||
context.textBaseline = 'alphabetic'; | |||||
context.translate(c.x, c.y); | |||||
context.rotate(angle); | |||||
context.fillText( | |||||
edge.label, | |||||
0, | |||||
(-size / 2) - 3 | |||||
); | |||||
context.restore(); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,25 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.canvas.edges.labels'); | |||||
/** | |||||
* This label renderer will just display the label on the curve of the edge. | |||||
* The label is rendered at half distance of the edge extremities, and is | |||||
* always oriented from left to right on the top side of the curve. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.labels.curvedArrow = | |||||
function(edge, source, target, context, settings) { | |||||
sigma.canvas.edges.labels.curve(edge, source, target, context, settings); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,96 @@ | |||||
;(function(undefined) { | |||||
'use strict'; | |||||
if (typeof sigma === 'undefined') | |||||
throw 'sigma is not declared'; | |||||
// Initialize packages: | |||||
sigma.utils.pkg('sigma.canvas.edges.labels'); | |||||
/** | |||||
* This label renderer will just display the label on the line of the edge. | |||||
* The label is rendered at half distance of the edge extremities, and is | |||||
* always oriented from left to right on the top side of the line. | |||||
* | |||||
* @param {object} edge The edge object. | |||||
* @param {object} source node The edge source node. | |||||
* @param {object} target node The edge target node. | |||||
* @param {CanvasRenderingContext2D} context The canvas context. | |||||
* @param {configurable} settings The settings function. | |||||
*/ | |||||
sigma.canvas.edges.labels.def = | |||||
function(edge, source, target, context, settings) { | |||||
if (typeof edge.label !== 'string' || source == target) | |||||
return; | |||||
var prefix = settings('prefix') || '', | |||||
size = edge[prefix + 'size'] || 1; | |||||
if (size < settings('edgeLabelThreshold')) | |||||
return; | |||||
if (0 === settings('edgeLabelSizePowRatio')) | |||||
throw '"edgeLabelSizePowRatio" must not be 0.'; | |||||
var fontSize, | |||||
x = (source[prefix + 'x'] + target[prefix + 'x']) / 2, | |||||
y = (source[prefix + 'y'] + target[prefix + 'y']) / 2, | |||||
dX = target[prefix + 'x'] - source[prefix + 'x'], | |||||
dY = target[prefix + 'y'] - source[prefix + 'y'], | |||||
sign = (source[prefix + 'x'] < target[prefix + 'x']) ? 1 : -1, | |||||
angle = Math.atan2(dY * sign, dX * sign); | |||||
// The font size is sublineraly proportional to the edge size, in order to | |||||
// avoid very large labels on screen. | |||||
// This is achieved by f(x) = x * x^(-1/ a), where 'x' is the size and 'a' | |||||
// is the edgeLabelSizePowRatio. Notice that f(1) = 1. | |||||
// The final form is: | |||||
// f'(x) = b * x * x^(-1 / a), thus f'(1) = b. Application: | |||||
// fontSize = defaultEdgeLabelSize if edgeLabelSizePowRatio = 1 | |||||
fontSize = (settings('edgeLabelSize') === 'fixed') ? | |||||
settings('defaultEdgeLabelSize') : | |||||
settings('defaultEdgeLabelSize') * | |||||
size * | |||||
Math.pow(size, -1 / settings('edgeLabelSizePowRatio')); | |||||
context.save(); | |||||
if (edge.active) { | |||||
context.font = [ | |||||
settings('activeFontStyle'), | |||||
fontSize + 'px', | |||||
settings('activeFont') || settings('font') | |||||
].join(' '); | |||||
context.fillStyle = | |||||
settings('edgeActiveColor') === 'edge' ? | |||||
(edge.active_color || settings('defaultEdgeActiveColor')) : | |||||
settings('defaultEdgeLabelActiveColor'); | |||||
} | |||||
else { | |||||
context.font = [ | |||||
settings('fontStyle'), | |||||
fontSize + 'px', | |||||
settings('font') | |||||
].join(' '); | |||||
context.fillStyle = | |||||
(settings('edgeLabelColor') === 'edge') ? | |||||
(edge.color || settings('defaultEdgeColor')) : | |||||
settings('defaultEdgeLabelColor'); | |||||
} | |||||
context.textAlign = 'center'; | |||||
context.textBaseline = 'alphabetic'; | |||||
context.translate(x, y); | |||||
context.rotate(angle); | |||||
context.fillText( | |||||
edge.label, | |||||
0, | |||||
(-size / 2) - 3 | |||||
); | |||||
context.restore(); | |||||
}; | |||||
}).call(this); |
@ -0,0 +1,31 @@ | |||||
sigma.renderers.edgeLabels | |||||
================== | |||||
Plugin developed by [Jack Miner](https://github.com/3ch01c). | |||||
Contact: 3ch01c@gmail.com | |||||
--- | |||||
## General | |||||
This plugin allows visualizing multiple parallel edges. | |||||
See the following [example](../../examples/parallel-edges.html) for full usage. | |||||
To use it, include all .js files under this folder. | |||||
## Edges | |||||
This plugin extends Sigma.js edges: | |||||
* **count** | |||||
* Represents the index of the edge in the set of parallel edges. Inversely proportional to the amplitude of the vertex of the edge curve. | |||||
* type: *number* | |||||
* default value: `0` | |||||
## Renderers | |||||
This plugin modifies | |||||
## Utils | |||||
This plugin modifies functions `sigma.utils.getQuadraticControlPoint` and `sigma.utils.getSelfLoopControlPoints` with an optional amplitude modifier parameters. |