Skip to content

Instantly share code, notes, and snippets.

@enjalot
Last active October 13, 2015 19:25
Show Gist options
  • Save enjalot/ebda1656976d90e2a636 to your computer and use it in GitHub Desktop.
Save enjalot/ebda1656976d90e2a636 to your computer and use it in GitHub Desktop.
morph experiment #3
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="sampler.js"></script>
<script src="matrix.js"></script>
<script src="polyk.js"></script>
</head>
<style>
body {
background-color: #192247;
}
</style>
<body>
<svg width=960 height=500>
<g transform="translate(-50,0)" opacity=0>
<path id="outer" fill="none" stroke="#fff" stroke-width="0.8" stroke-miterlimit="10" d="M174.7,85c-24.5,14-57,18-45.8,45.7
c9.5,23.4-28.2,15.1-45.8-25.7s20.5-65.8,45.8-65.8S196.7,72.5,174.7,85Z"/>
<path id="inner" fill="none" stroke="#fff" stroke-width="0.8" stroke-miterlimit="10" d="M128.4,64.4c-1.9-0.1-5.9,6-5.9,6s-2.3-3.6-1-7.4
c1.4-3.8,3.4-3.5,5-3.1C128.3,60.2,141.8,65.1,128.4,64.4z"/>
</g>
<g id="output">
</g>
</svg>
<script>
var svg = d3.select("svg");
var inner = d3.select("#inner")
var outer = d3.select("#outer")
var numSamples = 70;
var numRays = 250;
var numLines = 18;
var scale = 3;
var rotate = 90;
var frequency = 9;
var amp = 15;
var line = d3.svg.line()
.x(function(d) { return d.x })
.y(function(d) { return d.y })
.interpolate("linear-closed")
//.interpolate("cardinal-closed")
.interpolate("basis-closed")
var output = d3.select("#output")
function interpolate() {
var ins = Sampler.getSamples(inner.node(), numSamples);
var outs = Sampler.getSamples(outer.node(), numSamples);
// modulate the outer polygon
var o, theta;
for(var i = 0; i < outs.length; i++) {
o = outs[i];
//console.log(o)
theta = i/outs.length * Math.PI*2 * frequency;
o.x = o.x + o.perp.x * Math.sin(theta) * amp
o.y = o.y + o.perp.y * Math.sin(theta) * amp
}
//var ins = generateRect(20, 100, 99, 62, 63)
//var outs = generateRect(20, 0, 0, 310, 310)
var c = centroid(ins);
// we center our shapes on 0,0 to rotate about center
var zeroer = new Matrix()
.translate(-c.x, -c.y)
.scale(1)
var inmorph = new Matrix()
.scale(scale)
.rotate(rotate*0.1)
var morpher = new Matrix()
.scale(scale)
.rotate(-rotate)
var placer = new Matrix()
.translate(450, 240)
ins.forEach(function(d) {
transformer(d, zeroer)
transformer(d, inmorph)
transformer(d, placer)
})
outs.forEach(function(d) {
transformer(d, zeroer);
transformer(d, morpher)
transformer(d, placer);
})
//verify center
transformer(c, zeroer)
transformer(c, placer)
/*
output.append("circle")
.attr({
r: 5,
fill: "orange",
cx: c.x,
cy: c.y
})
*/
var rayd = generateRays(numRays);
var inpoly = toPolyK(ins)
var ind = rayd.map(function(ray) {
var point = PolyK.Raycast(inpoly, c.x, c.y, ray.dx, ray.dy);
//if(!point) point = { dist: 0 };
return {
x: c.x + ray.dx * point.dist,
y: c.y + ray.dy * point.dist,
perp: point.norm
}
})
var outpoly = toPolyK(outs)
var outd = rayd.map(function(ray) {
var point = PolyK.Raycast(outpoly, c.x, c.y, ray.dx, ray.dy);
//if(!point) point = { dist: 0 };
return {
x: c.x + ray.dx * point.dist,
y: c.y + ray.dy * point.dist,
perp: point.norm
}
})
//console.log(outd)
/*
var outdc = output.selectAll("circle.outd")
.data(outd)
outdc.enter().append("circle").classed("outd", true)
outdc.attr({
r: 5,
cx: function(d) { return d.x },
cy: function(d) { return d.y },
fill: "orange"
})*/
var lines = [];
d3.range(numLines+1).forEach(function(index) {
var samples = []
var ratio = index / numLines;
var i, x, y;
var last;
for(i = 0; i < ind.length; i++) {
x = ind[i].x * (1 - ratio) + outd[i].x * (ratio);
y = ind[i].y * (1 - ratio) + outd[i].y * (ratio);
var p = {x: x, y: y}
samples.push(p)
}
lines.push(samples)
})
// draw the lines we are interpolating along
/*
var interps = output.selectAll("line.interps")
.data(ind)
interps
.enter().append("line").classed("interps", true)
interps
.attr({
x1: function(d,i) { return d.x },
y1: function(d,i) { return d.y },
x2: function(d,i) { return outd[i].x },
y2: function(d,i) { return outd[i].y },
stroke: "#cf6ccf",
"stroke-width": 2,
"stroke-opacity": 0.2
})
*/
var blended = output.selectAll("path.blend")
.data(lines)
blended
.enter()
.append("path").classed("blend", true)
blended
.attr({
d: function(d) { return line(d) },
fill: "none",
stroke: "#ff005d",
"stroke-width": 2,
})
/*
var groups = output.selectAll("g.line").data(lines)
groups
.enter().append("g").classed("line", true)
var circles = groups
.selectAll("circle")
.data(function(d) { return d })
circles
.enter().append("circle")
circles
.attr({
r: 1,
fill: "white",
cx: function(d) { return d.x },
cy: function(d) { return d.y }
})
*/
}
interpolate();
function generateRect(num, x, y, width, height) {
var points = []
var sideNum = Math.floor(num/4) + 1;
// top
d3.range(sideNum).forEach(function(i) {
points.push({ x: x + i * width/sideNum, y: y })
})
// right
d3.range(sideNum).forEach(function(i) {
points.push({ x: x + width, y: y + i * height/sideNum })
})
// bottom
d3.range(sideNum).forEach(function(i) {
points.push({ x: x + width - i * width/sideNum, y: y + height })
})
// left
d3.range(sideNum).forEach(function(i) {
points.push({ x: x, y: y + height - i * height/sideNum })
})
return points;
}
function generateRays(num) {
var rays = d3.range(num).map(function(i) {
var theta = i/num*2*Math.PI
var dx = Math.sin(theta);
var dy = Math.cos(theta);
return {dx: dx, dy: dy}
})
return rays;
}
var x = 100;
var y = 50;
var r = 40;
var rotcolor = "#56fea2";
var rottxt = svg.append("text")
.text("rotation: " + rotate)
.attr({
y: y + r*2,
x: x - r,
fill: rotcolor,
"text-align": "center",
"font-family":"Roboto,Helvetica"
})
var roter = new electron()
.cx(100)
.cy(y+20)
.radius(r)
.color(rotcolor)
.cb(function(omega) {
rotate = omega*180/Math.PI;
rottxt.text("rotation: " + rotate.toFixed(0))
interpolate()
})
.update(svg)
var freqcolor = "#3dfbff";
var freqtxt = svg.append("text")
.text("frequency: " + frequency)
.attr({
y: y+120 + r*2,
x: x - r,
fill: freqcolor,
"text-align": "center",
"font-family":"Roboto,Helvetica"
})
var freqer = new electron()
.cx(100)
.cy(y+140)
.radius(r)
.color(freqcolor)
.cb(function(omega) {
frequency = omega * 5/Math.PI + 5
freqtxt.text("frequency: " + frequency.toFixed(0))
interpolate();
})
.update(svg)
var ampcolor = "#ffab3d";
var amptxt = svg.append("text")
.text("amp: " + amp)
.attr({
y: y+240 + r*2,
x: x - r/2,
fill: ampcolor,
"text-align": "center",
"font-family":"Roboto,Helvetica"
})
var amper = new electron()
.cx(100)
.cy(y+260)
.radius(r)
.color(ampcolor)
.cb(function(omega) {
amp = omega * 10/Math.PI + 10;
amptxt.text("amp: " + amp.toFixed(0))
interpolate();
})
.update(svg)
// "electron" dial component.
function electron() {
var cx = 75;
var cy = 75;
var radius = 50;
var color = "#000";
var dial;
var cb = function() {};
function rotateDial(omega) {
var nx = (radius-10) * Math.sin(omega);
var ny = (radius-10) * Math.cos(omega);
dial.attr({
cx: cx + nx,
cy: cy + ny
})
}
var drag = d3.behavior.drag()
.on("drag", function() {
var mx = d3.mouse(this)[0];
var my = d3.mouse(this)[1];
var omega = Math.atan2(mx - cx, my - cy);
rotateDial(omega);
if(cb) cb(omega)
})
this.update = function(g) {
var ring = g.append("circle")
.attr({
cx: cx,
cy: cy,
r: radius,
fill: "none",
stroke: color,
"stroke-width": 4
});
dial = g.append("circle")
.attr({
cx: cx + radius - 10,
cy: cy,
r: 10,
fill: color
});
dial.call(drag);
return this;
}
this.cb = function(arg) {
if(arg) {
cb = arg; return this;
}
return cb;
}
this.cx = function(arg) {
if(arg) {
cx = arg; return this;
}
return cx;
}
this.cy = function(arg) {
if(arg) {
cy = arg; return this;
}
return cy;
}
this.radius = function(arg) {
if(arg) {
radius = arg; return this;
}
return radius;
}
this.color = function(arg) {
if(arg) {
color = arg; return this;
}
return color;
}
this.rotateMe = function(omega) {
rotateDial(omega);
cb(omega)
};
return this;
}
var start = Date.now();
var duration = 20;
var pause = false;
d3.timer(function(elapsed) {
var now = Date.now();
if(now - start > duration) {
start = now;
} else {
return false;
}
var dt = elapsed * 0.00005 % 2*Math.PI
roter.rotateMe(Math.PI + dt);
freqer.rotateMe(-Math.PI + dt);
amper.rotateMe(Math.PI - dt);
return pause;
})
svg.on("click", function() {
pause = true;
})
</script>
</body>
function Matrix() {
/* http://bl.ocks.org/enjalot/65ae9c0fc95337107448
| a, b, tx |
| c, d, ty |
| 0, 0, 1 |
*/
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.tx = 0;
this.ty = 0;
this.s = 1;
this.ra = 1;
this.rb = 0;
this.rc = 0;
this.rd = 1;
}
Matrix.prototype.scale = function(s) {
this.s = s;
this.a *= s;
this.d *= s;
return this;
}
Matrix.prototype.translate = function(x,y) {
this.tx = x;
this.ty = y;
return this;
}
Matrix.prototype.rotate = function(deg) {
var sin = Math.sin(deg*Math.PI/180).toFixed(3);
var cos = Math.cos(deg*Math.PI/180).toFixed(3);
this.ra = cos;
this.rb = -sin;
this.rc = sin;
this.rd = cos;
this.update();
return this;
}
Matrix.prototype.update = function() {
this.a = this.ra * this.s;
this.b = this.rb * this.s;
this.c = this.rc * this.s;
this.d = this.rd * this.s;
return this;
}
function transformer(p, m){
// transform point
var x = p.x || 0;
var y = p.y || 0;
var x2 = m.a*x + m.b*y + m.tx;
var y2 = m.c*x + m.d*y + m.ty;
p.x = x2;
p.y = y2;
//return {x:x2, y:y2};
}
/*
PolyK library
url: http://polyk.ivank.net
Released under MIT licence.
Copyright (c) 2012 - 2014 Ivan Kuckir
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.
19. 5. 2014 - Problem with slicing fixed.
*/
var PolyK = {};
/*
Is Polygon self-intersecting?
O(n^2)
*/
PolyK.IsSimple = function(p)
{
var n = p.length>>1;
if(n<4) return true;
var a1 = new PolyK._P(), a2 = new PolyK._P();
var b1 = new PolyK._P(), b2 = new PolyK._P();
var c = new PolyK._P();
for(var i=0; i<n; i++)
{
a1.x = p[2*i ];
a1.y = p[2*i+1];
if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; }
else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; }
for(var j=0; j<n; j++)
{
if(Math.abs(i-j) < 2) continue;
if(j==n-1 && i==0) continue;
if(i==n-1 && j==0) continue;
b1.x = p[2*j ];
b1.y = p[2*j+1];
if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; }
else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; }
if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false;
}
}
return true;
}
PolyK.IsConvex = function(p)
{
if(p.length<6) return true;
var l = p.length - 4;
for(var i=0; i<l; i+=2)
if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false;
if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false;
if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false;
return true;
}
PolyK.GetArea = function(p)
{
if(p.length <6) return 0;
var l = p.length - 2;
var sum = 0;
for(var i=0; i<l; i+=2)
sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]);
sum += (p[0]-p[l]) * (p[l+1]+p[1]);
return - sum * 0.5;
}
PolyK.GetAABB = function(p)
{
var minx = Infinity;
var miny = Infinity;
var maxx = -minx;
var maxy = -miny;
for(var i=0; i<p.length; i+=2)
{
minx = Math.min(minx, p[i ]);
maxx = Math.max(maxx, p[i ]);
miny = Math.min(miny, p[i+1]);
maxy = Math.max(maxy, p[i+1]);
}
return {x:minx, y:miny, width:maxx-minx, height:maxy-miny};
}
PolyK.Reverse = function(p)
{
var np = [];
for(var j=p.length-2; j>=0; j-=2) np.push(p[j], p[j+1])
return np;
}
PolyK.Triangulate = function(p)
{
var n = p.length>>1;
if(n<3) return [];
var tgs = [];
var avl = [];
for(var i=0; i<n; i++) avl.push(i);
var i = 0;
var al = n;
while(al > 3)
{
var i0 = avl[(i+0)%al];
var i1 = avl[(i+1)%al];
var i2 = avl[(i+2)%al];
var ax = p[2*i0], ay = p[2*i0+1];
var bx = p[2*i1], by = p[2*i1+1];
var cx = p[2*i2], cy = p[2*i2+1];
var earFound = false;
if(PolyK._convex(ax, ay, bx, by, cx, cy))
{
earFound = true;
for(var j=0; j<al; j++)
{
var vi = avl[j];
if(vi==i0 || vi==i1 || vi==i2) continue;
if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;}
}
}
if(earFound)
{
tgs.push(i0, i1, i2);
avl.splice((i+1)%al, 1);
al--;
i= 0;
}
else if(i++ > 3*al) break; // no convex angles :(
}
tgs.push(avl[0], avl[1], avl[2]);
return tgs;
}
PolyK.ContainsPoint = function(p, px, py)
{
var n = p.length>>1;
var ax, ay = p[2*n-3]-py, bx = p[2*n-2]-px, by = p[2*n-1]-py;
//var lup = by > ay;
for(var i=0; i<n; i++)
{
ax = bx; ay = by;
bx = p[2*i ] - px;
by = p[2*i+1] - py;
if(ay==by) continue;
lup = by>ay;
}
var depth = 0;
for(var i=0; i<n; i++)
{
ax = bx; ay = by;
bx = p[2*i ] - px;
by = p[2*i+1] - py;
if(ay< 0 && by< 0) continue; // both "up" or both "down"
if(ay> 0 && by> 0) continue; // both "up" or both "down"
if(ax< 0 && bx< 0) continue; // both points on the left
if(ay==by && Math.min(ax,bx)<=0) return true;
if(ay==by) continue;
var lx = ax + (bx-ax)*(-ay)/(by-ay);
if(lx==0) return true; // point on edge
if(lx> 0) depth++;
if(ay==0 && lup && by>ay) depth--; // hit vertex, both up
if(ay==0 && !lup && by<ay) depth--; // hit vertex, both down
lup = by>ay;
}
//console.log(depth);
return (depth & 1) == 1;
}
PolyK.Slice = function(p, ax, ay, bx, by)
{
if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)];
var a = new PolyK._P(ax, ay);
var b = new PolyK._P(bx, by);
var iscs = []; // intersections
var ps = []; // points
for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1]));
for(var i=0; i<ps.length; i++)
{
var isc = new PolyK._P(0,0);
isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc);
var fisc = iscs[0];
var lisc = iscs[iscs.length-1];
if(isc && (fisc==null || PolyK._P.dist(isc,fisc)>1e-10) && (lisc==null || PolyK._P.dist(isc,lisc)>1e-10 ) )//&& (isc.x!=ps[i].x || isc.y!=ps[i].y) )
{
isc.flag = true;
iscs.push(isc);
ps.splice(i+1,0,isc);
i++;
}
}
if(iscs.length <2) return [p.slice(0)];
var comp = function(u,v) { return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); }
iscs.sort(comp);
//console.log("Intersections: "+iscs.length, JSON.stringify(iscs));
var pgs = [];
var dir = 0;
while(iscs.length > 0)
{
var n = ps.length;
var i0 = iscs[0];
var i1 = iscs[1];
//if(i0.x==i1.x && i0.y==i1.y) { iscs.splice(0,2); continue;}
var ind0 = ps.indexOf(i0);
var ind1 = ps.indexOf(i1);
var solved = false;
//console.log(i0, i1);
if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
else
{
i0 = iscs[1];
i1 = iscs[0];
ind0 = ps.indexOf(i0);
ind1 = ps.indexOf(i1);
if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
}
if(solved)
{
dir--;
var pgn = PolyK._getPoints(ps, ind0, ind1);
pgs.push(pgn);
ps = PolyK._getPoints(ps, ind1, ind0);
i0.flag = i1.flag = false;
iscs.splice(0,2);
if(iscs.length == 0) pgs.push(ps);
}
else { dir++; iscs.reverse(); }
if(dir>1) break;
}
var result = [];
for(var i=0; i<pgs.length; i++)
{
var pg = pgs[i];
var npg = [];
for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y);
result.push(npg);
}
return result;
}
PolyK.Raycast = function(p, x, y, dx, dy, isc)
{
var l = p.length - 2;
var tp = PolyK._tp;
var a1 = tp[0], a2 = tp[1],
b1 = tp[2], b2 = tp[3], c = tp[4];
a1.x = x; a1.y = y;
a2.x = x+dx; a2.y = y+dy;
if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}};
isc.dist = Infinity;
for(var i=0; i<l; i+=2)
{
b1.x = p[i ]; b1.y = p[i+1];
b2.x = p[i+2]; b2.y = p[i+3];
var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc);
}
b1.x = b2.x; b1.y = b2.y;
b2.x = p[0]; b2.y = p[1];
var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, (p.length/2)-1, isc);
return (isc.dist != Infinity) ? isc : null;
}
PolyK.ClosestEdge = function(p, x, y, isc)
{
var l = p.length - 2;
var tp = PolyK._tp;
var a1 = tp[0],
b1 = tp[2], b2 = tp[3], c = tp[4];
a1.x = x; a1.y = y;
if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}};
isc.dist = Infinity;
for(var i=0; i<l; i+=2)
{
b1.x = p[i ]; b1.y = p[i+1];
b2.x = p[i+2]; b2.y = p[i+3];
PolyK._pointLineDist(a1, b1, b2, i>>1, isc);
}
b1.x = b2.x; b1.y = b2.y;
b2.x = p[0]; b2.y = p[1];
PolyK._pointLineDist(a1, b1, b2, l>>1, isc);
var idst = 1/isc.dist;
isc.norm.x = (x-isc.point.x)*idst;
isc.norm.y = (y-isc.point.y)*idst;
return isc;
}
PolyK._pointLineDist = function(p, a, b, edge, isc)
{
var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = dot / len_sq;
var xx, yy;
if (param < 0 || (x1 == x2 && y1 == y2)) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = x - xx;
var dy = y - yy;
var dst = Math.sqrt(dx * dx + dy * dy);
if(dst<isc.dist)
{
isc.dist = dst;
isc.edge = edge;
isc.point.x = xx;
isc.point.y = yy;
}
}
PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc)
{
var nrl = PolyK._P.dist(a1, c);
if(nrl<isc.dist)
{
var ibl = 1/PolyK._P.dist(b1, b2);
var nx = -(b2.y-b1.y)*ibl;
var ny = (b2.x-b1.x)*ibl;
var ddot = 2*(dx*nx+dy*ny);
isc.dist = nrl;
isc.norm.x = nx;
isc.norm.y = ny;
isc.refl.x = -ddot*nx+dx;
isc.refl.y = -ddot*ny+dy;
isc.edge = edge;
}
}
PolyK._getPoints = function(ps, ind0, ind1)
{
var n = ps.length;
var nps = [];
if(ind1<ind0) ind1 += n;
for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]);
return nps;
}
PolyK._firstWithFlag = function(ps, ind)
{
var n = ps.length;
while(true)
{
ind = (ind+1)%n;
if(ps[ind].flag) return ind;
}
}
PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
}
PolyK._RayLineIntersection = function(a1, a2, b1, b2, c)
{
var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
var day = (a1.y-a2.y), dby = (b1.y-b2.y);
var Den = dax*dby - day*dbx;
if (Den == 0) return null; // parallel
var A = (a1.x * a2.y - a1.y * a2.x);
var B = (b1.x * b2.y - b1.y * b2.x);
var I = c;
var iDen = 1/Den;
I.x = ( A*dbx - dax*B ) * iDen;
I.y = ( A*dby - day*B ) * iDen;
if(!PolyK._InRect(I, b1, b2)) return null;
if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null;
if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null;
return I;
}
PolyK._GetLineIntersection = function(a1, a2, b1, b2, c)
{
var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
var day = (a1.y-a2.y), dby = (b1.y-b2.y);
var Den = dax*dby - day*dbx;
if (Den == 0) return null; // parallel
var A = (a1.x * a2.y - a1.y * a2.x);
var B = (b1.x * b2.y - b1.y * b2.x);
var I = c;
I.x = ( A*dbx - dax*B ) / Den;
I.y = ( A*dby - day*B ) / Den;
if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I;
return null;
}
PolyK._InRect = function(a, b, c) // a in rect (b,c)
{
var minx = Math.min(b.x,c.x), maxx = Math.max(b.x,c.x);
var miny = Math.min(b.y,c.y), maxy = Math.max(b.y,c.y);
if (minx == maxx) return (miny<=a.y && a.y<=maxy);
if (miny == maxy) return (minx<=a.x && a.x<=maxx);
//return (minx <= a.x && a.x <= maxx && miny <= a.y && a.y <= maxy)
return (minx <= a.x+1e-10 && a.x-1e-10 <= maxx && miny <= a.y+1e-10 && a.y-1e-10 <= maxy) ;
}
PolyK._convex = function(ax, ay, bx, by, cx, cy)
{
return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0;
}
PolyK._P = function(x,y)
{
this.x = x;
this.y = y;
this.flag = false;
}
PolyK._P.prototype.toString = function()
{
return "Point ["+this.x+", "+this.y+"]";
}
PolyK._P.dist = function(a,b)
{
var dx = b.x-a.x;
var dy = b.y-a.y;
return Math.sqrt(dx*dx + dy*dy);
}
PolyK._tp = [];
for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0));
var Sampler = function() {}
Sampler.getSamples = function(path, num) {
var len = path.getTotalLength()
var p, t;
var result = []
for(var i = 0; i < num; i++) {
p = path.getPointAtLength(i * len/num);
t = Sampler.getTangent(path, i/num * 100);
result.push({
x: p.x,
y: p.y,
point: p,
tangent: t,
perp: Sampler.rotate2d(t.v, 90)
});
}
return result
}
Sampler.getTangent = function(path, percent) {
// returns a normalized vector that describes the tangent
// at the point that is found at *percent* of the path's length
var fraction = percent/100;
if(fraction < 0) fraction = 0;
if(fraction > 0.99) fraction = 1;
var len = path.getTotalLength();
var point1 = path.getPointAtLength(fraction * len - 0.1);
var point2 = path.getPointAtLength(fraction * len + 0.1);
var vector = { x: point2.x - point1.x, y: point2.y - point1.y }
var magnitude = Math.sqrt(vector.x*vector.x + vector.y*vector.y);
vector.x /= magnitude;
vector.y /= magnitude;
return {p: point1, v: vector };
}
Sampler.rotate2d = function(vector, angle) {
//rotate a vector
angle *= Math.PI/180; //convert to radians
return {
x: vector.x * Math.cos(angle) - vector.y * Math.sin(angle),
y: vector.x * Math.sin(angle) + vector.y * Math.cos(angle)
}
}
// we average the location of all the array's points to get the center
function centroid(samples) {
var avg = {x:0, y:0};
for(var i = 0; i < samples.length; i++) {
avg.x += samples[i].x;
avg.y += samples[i].y;
}
avg.x /= samples.length;
avg.y /= samples.length;
return avg;
}
// The PolyK library expects a flat array like [x,y,x,y...]
function toPolyK(samples) {
var poly = []
for(var i = 0; i < samples.length; i++) {
poly.push(samples[i].x);
poly.push(samples[i].y);
}
return poly;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment