From 8bab8fade3c4447be74ade79d1b1364e4116bbfb Mon Sep 17 00:00:00 2001 From: Pomax Date: Wed, 21 Sep 2016 21:20:25 -0700 Subject: [PATCH] buy me coffee? --- article.js | 2 +- components/sections/comments/index.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/article.js b/article.js index b538a9b2..834d21fd 100644 --- a/article.js +++ b/article.js @@ -86,4 +86,4 @@ setup:this.setupCubic,draw:this.draw}),r.createElement("p",null,"Curve/curve int }})),r.createElement("p",null,"The difference is somewhere in the actual hermite matrix, since the ",r.createElement("em",null,"t")," and coordinate values are identical, so let's solve that matrix equasion:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/8a42b24fca3aaf6b8ec08e84b7e91c43e26e8acf.svg",style:{width:"28.575rem",height:"5.54985rem"}})),r.createElement("p",null,"We left-multiply both sides by the inverse of the Bézier matrix, to get rid of the Bézier matrix on the right side of the equals sign:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0e111d6e846f4d7204dec484005f74993e66c6c9.svg",style:{width:"58.19985rem",height:"5.70015rem"}})),r.createElement("p",null,"Which gives us:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f94b80113772d90a4fbc93d4495cb5767e5c8123.svg",style:{width:"12.6rem",height:"5.47515rem"}})),r.createElement("p",null,"Multiplying this ",r.createElement("strong",null,r.createElement("em",null,"A"))," with our coordinates will give us a proper Bézier matrix expression again:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d088274e440ceeac2916a0f32176682d776c1c57.svg",style:{width:"31.725rem",height:"5.47515rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/9e68f80b270d3445d9f9cb28ff2c5aed219aa9d2.svg",style:{width:"25.650000000000002rem",height:"6.60015rem"}})),r.createElement("p",null,"So a Catmull-Rom to Bézier conversion, based on coordinates, requires turning the Catmull-Rom coordinates on the left into the Bézier coordinates on the right (with τ being our tension factor):"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f0c5a707b590eaf8899a927ce39fd186a6acecf3.svg",style:{width:"18.07515rem",height:"6.67485rem"}})),r.createElement("p",null,"And the other way around, a Bézier to Catmull-Rom conversion requires turning the Bézier coordinates on the left this time into the Catmull-Rom coordinates on the right. Note that there is no tension this time, because Bézier curves don't have any. Converting from Bézier to Catmull-Rom is simply a default-tension Catmull-Rom curve:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/51da95daf2645abd9903a4e28749a6d01826625c.svg",style:{width:"21.150000000000002rem",height:"5.625rem"}})),r.createElement("p",null,"Done. We can now draw the curves we want using either Bézier curves or Catmull-Rom splines, the choice mostly being which drawing algorithms we have natively available."))}});e.exports=a},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(223),o=n(226),s=r.createClass({displayName:"CatmullRomMoulding",statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},getDefaultProps:function(){return{title:"Creating a Catmull-Rom curve from three points"}},setup:function(e){e.setPanelCount(3),e.lpts=[{x:56,y:153},{x:144,y:83},{x:188,y:185}],e.distance=0},convert:function(e,t,n,r){var i=.5;return[t,{x:t.x+(n.x-e.x)/(6*i),y:t.y+(n.y-e.y)/(6*i)},{x:n.x-(r.x-t.x)/(6*i),y:n.y-(r.y-t.y)/(6*i)},n]},draw:function(e){e.reset(),e.setColor("lightblue"),e.drawGrid(10,10);var t=e.lpts;e.setColor("black"),e.setFill("black"),t.forEach(function(t,n){e.drawCircle(t,3),e.text("point "+(n+1),t,{x:10,y:7})});var n=e.getPanelWidth(),r=e.getPanelHeight(),i={x:n,y:0};e.setColor("lightblue"),e.drawGrid(10,10,i),e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},i),t.forEach(function(t,n){e.drawCircle(t,3,i)});var a=t[0],o=t[1],s=t[2],l=s.x-a.x,u=s.y-a.y,c=Math.sqrt(l*l+u*u);l/=c,u/=c,e.drawLine(a,s,i);var h={x:a.x+(s.x-o.x)-e.distance*l,y:a.y+(s.y-o.y)-e.distance*u},d={x:a.x+(s.x-o.x)+e.distance*l,y:a.y+(s.y-o.y)+e.distance*u},p=e.utils.lli4(a,s,o,{x:(h.x+d.x)/2,y:(h.y+d.y)/2});e.setColor("blue"),e.drawCircle(p,3,i),e.drawLine(t[1],p,i),e.setColor("#666"),e.drawLine(p,h,i),e.drawLine(p,d,i),e.setFill("blue"),e.text("p0",h,{x:-20+i.x,y:i.y+2}),e.text("p4",d,{x:10+i.x,y:i.y+2}),e.setColor("red"),e.drawCircle(h,3,i),e.drawLine(o,h,i),e.drawLine(a,{x:a.x+(o.x-h.x)/5,y:a.y+(o.y-h.y)/5},i),e.setColor("#00FF00"),e.drawCircle(d,3,i),e.drawLine(o,d,i),e.drawLine(s,{x:s.x+(d.x-o.x)/5,y:s.y+(d.y-o.y)/5},i);var f=new e.Bezier(this.convert(h,a,o,s)),m=new e.Bezier(this.convert(a,o,s,d));e.setColor("lightgrey"),e.drawCurve(f,i),e.drawCurve(m,i),i.x+=n,e.setColor("lightblue"),e.drawGrid(10,10,i),e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},i),e.drawCurve(f,i),e.drawCurve(m,i),e.drawPoints(f.points,i),e.drawPoints(m.points,i),e.setColor("lightgrey"),e.drawLine(f.points[0],f.points[1],i),e.drawLine(f.points[2],m.points[1],i),e.drawLine(m.points[2],m.points[3],i)},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Now, we saw how to fit a Bézier curve to three points, but if Catmull-Rom curves go through points, why can't we just use those to do curve fitting, instead?"),r.createElement("p",null,"As a matter of fact, we can, but there's a difference between the kind of curve fitting we did in the previous section, and the kind of curve fitting that we can do with Catmull-Rom curves. In the previous section we came up with a single curve that goes through three points. There was a decent amount of maths and computation involved, and the end result was three or four coordinates that described a single curve, depending on whether we were fitting a quadratic or cubic curve."),r.createElement("p",null,"Using Catmull-Rom curves, we need virtually no computation, but even though we end up with one Catmull-Rom curve of ",r.createElement("i",null,"n")," points, in order to draw the equivalent curve using cubic Bézier curves we need a massive ",r.createElement("i",null,"3n-1")," points (and that's without double-counting points that are shared by consecutive cubic curves)."),r.createElement("p",null,'In the following graphic, on the left we see three points that we want to draw a Catmull-Rom curve through (which we can move around freely, by the way), with in the second panel some of the "interesting" Catmull-Rom information: in black there\'s the baseline start--end, which will act as tangent orientation for the curve at point p2. We also see a virtual point p0 and p4, which are initially just point p2 reflected over the baseline. However, by using the up and down cursor key we can offset these points parallel to the baseline. Why would we want to do this? Because the line p0--p2 acts as departure tangent at p1, and the line p2--p4 acts as arrival tangent at p3. Play around with the graphic a bit to get an idea of what all of that meant:'),r.createElement(i,{preset:"threepanel",title:"Catmull-Rom curve fitting",setup:this.setup,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,"As should be obvious by now, Catmull-Rom curves are great for \"fitting a curvature to some points\", but if we want to convert that curve to Bézier form we're going to end up with a lot of separate (but visually joined) Bézier curves. Depending on what we want to do, that'll be either unnecessary work, or exactly what we want: which it is depends entirely on you."))}});e.exports=o(s)},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(223),o=Math.atan2,s=Math.sqrt,l=Math.sin,u=Math.cos,c=r.createClass({displayName:"PolyBezier",getDefaultProps:function(){return{title:"Forming poly-Bézier curves"}},setupQuadratic:function(e){var t=e.getPanelWidth(),n=e.getPanelHeight(),r=t/2,i=n/2,a=40,o=[{x:r,y:a},{x:t-a,y:a},{x:t-a,y:i},{x:t-a,y:n-a},{x:r,y:n-a},{x:a,y:n-a},{x:a,y:i},{x:a,y:a}];e.lpts=o},setupCubic:function(e){var t=e.getPanelWidth(),n=e.getPanelHeight(),r=t/2,i=n/2,a=40,o=(t-2*a)/2,s=.55228,l=s*o,u=[{x:r,y:a},{x:r+l,y:a},{x:t-a,y:i-l},{x:t-a,y:i},{x:t-a,y:i+l},{x:r+l,y:n-a},{x:r,y:n-a},{x:r-l,y:n-a},{x:a,y:i+l},{x:a,y:i},{x:a,y:i-l},{x:r-l,y:a}];e.lpts=u},movePointsQuadraticLD:function(e,t){for(var n,r,i,a=1;a<4;a++)n=t+(2*a-2)+e.lpts.length,n=e.lpts[n%e.lpts.length],r=t+(2*a-1),r=e.lpts[r%e.lpts.length],i=t+2*a,i=e.lpts[i%e.lpts.length],i.x=r.x+(r.x-n.x),i.y=r.y+(r.y-n.y);i=t+6,i=e.lpts[i%e.lpts.length],e.problem=i},movePointsCubicLD:function(e,t){var n,r;t%3===1?(r=t-1,r+=r<0?e.lpts.length:0,n=t-2,n+=n<0?e.lpts.length:0):(r=(t+1)%e.lpts.length,n=(t+2)%e.lpts.length),r=e.lpts[r],n=e.lpts[n],n.x=r.x+(r.x-e.mp.x),n.y=r.y+(r.y-e.mp.y)},linkDerivatives:function(e,t){if(t.mp){var n=8===t.lpts.length,r=t.mp_idx;n?r%2!==0&&this.movePointsQuadraticLD(t,r):r%3!==0&&this.movePointsCubicLD(t,r)}},movePointsQuadraticDirOnly:function(e,t){var n,r,i;[-1,1].forEach(function(a){n=e.mp,r=t+a+e.lpts.length,r=e.lpts[r%e.lpts.length],i=t+2*a+e.lpts.length,i=e.lpts[i%e.lpts.length];var c=o(r.y-n.y,r.x-n.x),h=i.x-r.x,d=i.y-r.y,p=s(h*h+d*d);i.x=r.x+p*u(c),i.y=r.y+p*l(c)}),i=t+4,i=e.lpts[i%e.lpts.length],e.problem=i},movePointsCubicDirOnly:function(e,t){var n,r;t%3===1?(r=t-1,r+=r<0?e.lpts.length:0,n=t-2,n+=n<0?e.lpts.length:0):(r=(t+1)%e.lpts.length,n=(t+2)%e.lpts.length),r=e.lpts[r],n=e.lpts[n];var i=o(r.y-e.mp.y,r.x-e.mp.x),a=n.x-r.x,c=n.y-r.y,h=s(a*a+c*c);n.x=r.x+h*u(i),n.y=r.y+h*l(i)},linkDirection:function(e,t){if(t.mp){var n=8===t.lpts.length,r=t.mp_idx;n?r%2!==0&&this.movePointsQuadraticDirOnly(t,r):r%3!==0&&this.movePointsCubicDirOnly(t,r)}},bufferPoints:function(e,t){t.bpts=JSON.parse(JSON.stringify(t.lpts))},moveQuadraticPoint:function(e,t){this.moveCubicPoint(e,t),[-1,1].forEach(function(n){var r=t-n+e.lpts.length;r=e.lpts[r%e.lpts.length];var i=t-2*n+e.lpts.length;i=e.lpts[i%e.lpts.length];var a=t-3*n+e.lpts.length;a=e.lpts[a%e.lpts.length];var c=o(i.y-r.y,i.x-r.x),h=a.x-i.x,d=a.y-i.y,p=s(h*h+d*d);a.x=i.x+p*u(c),a.y=i.y+p*l(c)});var n=t+4;n=e.lpts[n%e.lpts.length],e.problem=n},moveCubicPoint:function(e,t){var n=e.bpts[t],r=e.lpts[t],i=r.x-n.x,a=r.y-n.y,o=e.lpts.length,s=t-1+o,l=t+1,u=e.bpts[s%o],c=e.bpts[l%o],h=e.lpts[s%o],d=e.lpts[l%o];return h.x=u.x+i,h.y=u.y+a,d.x=c.x+i,d.y=c.y+a,{x:i,y:a}},modelCurve:function(e,t){if(t.mp){var n=8===t.lpts.length,r=t.mp_idx;n?r%2!==0?this.movePointsQuadraticDirOnly(t,r):this.moveQuadraticPoint(t,r):r%3!==0?this.movePointsCubicDirOnly(t,r):this.moveCubicPoint(t,r)}},draw:function(e,t){e.reset();var n=e.lpts,r=8===n.length,i=r?new e.Bezier(n[0],n[1],n[2]):new e.Bezier(n[0],n[1],n[2],n[3]);e.drawSkeleton(i,!1,!0),e.drawCurve(i);var a=r?new e.Bezier(n[2],n[3],n[4]):new e.Bezier(n[3],n[4],n[5],n[6]);e.drawSkeleton(a,!1,!0),e.drawCurve(a);var o=r?new e.Bezier(n[4],n[5],n[6]):new e.Bezier(n[6],n[7],n[8],n[9]);e.drawSkeleton(o,!1,!0),e.drawCurve(o);var s=r?new e.Bezier(n[6],n[7],n[0]):new e.Bezier(n[9],n[10],n[11],n[0]);e.drawSkeleton(s,!1,!0),e.drawCurve(s),e.problem&&(e.setColor("red"),e.drawCircle(e.problem,5))},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Much like lines can be chained together to form polygons, Bézier curves can be chained together to form poly-Béziers, and the only trick required is to make sure that:"),r.createElement("ol",null,r.createElement("li",null,"the end point of each section is the starting point of the following section, and"),r.createElement("li",null,"the derivatives across that dual point line up.")),r.createElement("p",null,"Unless, of course, you want discontinuities; then you don't even need 2."),r.createElement("p",null,"We'll cover three forms of poly-Bézier curves in this section. First, we'll look at the kind that just follows point 1. where the end point of a segment is the same point as the start point of the next segment. This leads to poly-Béziers that are pretty hard to work with, but they're the easiest to implement:"),r.createElement(i,{preset:"poly",title:"Unlinked quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw}),r.createElement(i,{preset:"poly",title:"Unlinked cubic poly-Bézier",setup:this.setupCubic,draw:this.draw}),r.createElement("p",null,'Dragging the control points around only affects the curve segments that the control point belongs to, and moving an on-curve point leaves the control points where they are, which is not the most useful for practical modelling purposes. So, let\'s add in the logic we need to make things a little better. We\'ll start by linking up control points by ensuring that the "incoming" derivative at an on-curve point is the same as it\'s "outgoing" derivative:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/37740bb1a0b7b1ff48bf3454e52295fc717cacbb.svg",style:{width:"8.400150000000002rem",height:"1.27485rem"}})),r.createElement("p",null,"We can effect this quite easily, because we know that the vector from a curve's last control point to its last on-curve point is equal to the derivative vector. If we want to ensure that the first control point of the next curve matches that, all we have to do is mirror that last control point through the last on-curve point. And mirroring any point A through any point B is really simple:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ce6e3939608c4ed0598107b06543c2301b91bb7f.svg",style:{width:"21.97485rem",height:"2.7rem"}})),r.createElement("p",null,"So let's implement that and see what it gets us. The following two graphics show a quadratic and a cubic poly-Bézier curve again, but this time moving the control points around moves others, too. However, you might see something unexpected going on for quadratic curves..."),r.createElement(i,{preset:"poly",title:"Loosely connected quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw,onMouseMove:this.linkDerivatives}),r.createElement(i,{preset:"poly",title:"Loosely connected cubic poly-Bézier",setup:this.setupCubic,draw:this.draw,onMouseMove:this.linkDerivatives}),r.createElement("p",null,"As you can see, quadratic curves are particularly ill-suited for poly-Bézier curves, as all the control points are effectively linked. Move one of them, and you move all of them. Not only that, but if we move the on-curve points, it's possible to get a situation where a control point's positions is different depending on whether it's the reflection of its left or right neighbouring control point: we can't even form a proper rule-conforming curve! This means that we cannot use quadratic poly-Béziers for anything other than really, really simple shapes. And even then, they're probably the wrong choice. Cubic curves are pretty decent, but the fact that the derivatives are linked means we can't manipulate curves as well as we might if we relaxed the constraints a little."),r.createElement("p",null,"So: let's relax the requirement a little."),r.createElement("p",null,"We can change the constraint so that we still preserve the ",r.createElement("em",null,"angle")," of the derivatives across sections (so transitions from one section to the next will still look natural), but give up the requirement that they should also have the same ",r.createElement("em",null,"vector length"),". Doing so will give us a much more useful kind of poly-Bézier curve:"),r.createElement(i,{preset:"poly",title:"Loosely connected quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw,onMouseMove:this.linkDirection}),r.createElement(i,{preset:"poly",title:"Loosely connected cubic poly-Bézier",setup:this.setupCubic,draw:this.draw,onMouseMove:this.linkDirection}),r.createElement("p",null,"Cubic curves are now better behaved when it comes to dragging control points around, but the quadratic poly-Bézier still has the problem that moving one control points will move the control points and may ending up defining \"the next\" control point in a way that doesn't work. Quadratic curves really aren't very useful to work with..."),r.createElement("p",null,"Finally, we also want to make sure that moving the on-curve coordinates preserves the relative positions of the associated control points. With that, we get to the kind of curve control that you might be familiar with from applications like Photoshop, Inkscape, Blender, etc."),r.createElement(i,{preset:"poly",title:"Loosely connected quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw,onMouseDown:this.bufferPoints,onMouseMove:this.modelCurve}),r.createElement(i,{preset:"poly",title:"Loosely connected cubic poly-Bézier",setup:this.setupCubic,draw:this.draw,onMouseDown:this.bufferPoints,onMouseMove:this.modelCurve}),r.createElement("p",null,'Again, we see that cubic curves are now rather nice to work with, but quadratic curves have a new, very serious problem: we can move an on-curve point in such a way that we can\'t compute what needs to "happen next". Move the top point down, below the left and right points, for instance. There is no way to preserve correct control points without a kink at the bottom point. Quadratic curves: just not that good...'),r.createElement("p",null,'A final improvement is to offer fine-level control over which points behave which, so that you can have "kinks" or individually controlled segments when you need them, with nicely well-behaved curves for the rest of the path. Implementing that, is left as an excercise for the reader.'))}});e.exports=c},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(223),o=["unite","intersect","exclude","subtract"],s=r.createClass({displayName:"Shapes",getDefaultProps:function(){return{title:"Boolean shape operations"}},getInitialState:function(){return{mode:o[0]}},setMode:function(e){this.setState({mode:e})},formPath:function(e,t,n,r,i){t=t||0,n=n||0;var a=30,o=a/2;r=r||8*a,i=i||4*a;var s=r/2,l=i/2,u=s/3,c=l/3,h=e.Paper,d=h.Path,p=h.Point,f=new d;return f.moveTo(new p(t-s+2*a,n-l)),f.cubicCurveTo(new p(t-s+o,n-l+o),new p(t-s+o,n+l-o),new p(t-s+2*a,n+l)),f.cubicCurveTo(new p(t-u,n+c),new p(t+u,n+c),new p(t+s-2*a,n+l)),f.cubicCurveTo(new p(t+s-o,n+l-o),new p(t+s-o,n-l+o),new p(t+s-2*a,n-l)),f.cubicCurveTo(new p(t+u,n-c),new p(t-u,n-c),new p(t-s+2*a,n-l)),f.closePath(!0),f.strokeColor="rgb(100,100,255)",f},setup:function(e){var t=e.getPanelWidth(),n=40,r=t/2,i=t/2;e.c1=this.formPath(e,r,i),r+=n,i+=n,e.c2=this.formPath(e,r,i),this.state.mode=o[0]},onMouseMove:function(e,t){var n=e.offsetX,r=e.offsetY;t.c2.position={x:n,y:r}},draw:function(e){e.c3&&e.c3.remove();var t=e.c1,n=e.c2,r=t[this.state.mode].bind(t),i=e.c3=r(n);i.strokeColor="red",i.fillColor="rgba(255,100,100,0.4)",e.Paper.view.draw()},render:function(){var e=this;return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"We can apply the topics covered so far in this primer to effect boolean shape operations: getting the union, intersection, or exclusion, between two or more shapes that involve Bézier curves. For simplicity (well.. sort of, more homogeneity), we'll be looking at Poly-Bézier shapes only, but a shape that consists of a mix of lines and Bézier curves is technically a simplification (although it does mean we need to write a definition for the class of shapes that mix lines and Bézier curves. Since poly-Bézier curves are a superset, we'll be using those in the following examples)"),r.createElement("p",null,"The procedure for performing boolean operations consists, broadly, of four steps:"),r.createElement("ol",null,r.createElement("li",null,"Find the intersection points between both shapes,"),r.createElement("li",null,"cut up the shapes into multiple sections between these intersections,"),r.createElement("li",null,"discard any section that isn't part of the desired operation's resultant shape, and"),r.createElement("li",null,"link up the remaining sections to form the new shape.")),r.createElement("p",null,"Finding all intersections between two poly-Bézier curves, or any poly-line-section shape, is similar to the iterative algorithm discussed in the section on curve/curve intersection. For each segment in the poly-Bézier curve we check whether its bounding box overlaps with any of the segment bounding boxes in the other poly-Bézier curve. If so, we run normal intersection detection."),r.createElement("p",null,"After we found all intersection points, we split up our poly-Bézier curves, making sure to record which of the newly formed poly-Bézier curves might potentially link up at the points we split the originals up at. This will let us quickly glue poly-Bézier curves back together after the next step."),r.createElement("p",null,"Once we have all the new poly-Bézier curves, we run the first step of the desired boolean operation."),r.createElement("ul",null,r.createElement("li",null,'Union: discard all poly-Bézier curves that lie "inside" our union of our shapes. E.g. if we want the union of two overlapping circles, the resulting shape is the outline.'),r.createElement("li",null,'Intersection: discard all poly-Bézier curves that lie "outside" the intersection of the two shapes. E.g. if we want the intersection of two overlapping circles, the resulting shape is the tapered ellipse where they overlap.'),r.createElement("li",null,"Exclusion: none of the sections are discarded, but we will need to link the shapes back up in a special way. Flip any section that would qualify for removal under UNION rules.")),r.createElement("table",{className:"sketch"},r.createElement("tbody",null,r.createElement("tr",null,r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_base.gif",height:"169px"}),r.createElement("p",null,"Two overlapping shapes.")),r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_union.gif",height:"169px"}),r.createElement("p",null,"The unified region.")),r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_intersection.gif",height:"169px"}),r.createElement("p",null,"Their intersection.")),r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_exclusion.gif",height:"169px"}),r.createElement("p",null,"Their exclusion regions."))))),r.createElement("p",null,'The main complication in the outlined procedure here is determining how sections qualify in terms of being "inside" and "outside" of our shapes. For this, we need to be able to perform point-in-shape detection, for which we\'ll use a classic algorithm: getting the "crossing number" by using ray casting, and then testing for "insidedness" by applying the ',r.createElement("a",{href:"http://folk.uio.no/bjornw/doc/bifrost-ref/bifrost-ref-12.html"},"even-odd rule"),': For any point and any shape, we can cast a ray from our point, to some point that we know lies outside of the shape (such as a corner of our drawing surface). We then count how many times that line crosses our shape (remember that we can perform line/curve intersection detection quite easily). If the number of times it crosses the shape\'s outline is even, the point did not actually lie inside our shape. If the number of intersections is odd, our point did lie inside out shape. With that knowledge, we can decide whether to treat a section that such a point lies on "needs removal" (under union rules), "needs preserving" (under intersection rules), or "needs flipping" (under exclusion rules).'),r.createElement("p",null,"These operations are expensive, and implementing your own code for this is generally a bad idea if there is already a geometry package available for your language of choice. In this case, for JavaScript the most excellent ",r.createElement("a",{href:"http://paperjs.org"},"Paper.js")," already comes with all the code in place to perform efficient boolean shape operations, so rather that implement an inferior version here, I can strongly recommend the Paper.js library if you intend to do any boolean shape work."),r.createElement("p",null,"The following graphic shows Paper.js doing its thing for two shapes: one static, and one that is linked to your mouse pointer. If you move the mouse around, you'll see how the shape intersections are resolved. The base shapes are outlined in blue, and the boolean result is coloured red."),r.createElement(i,{preset:"simple",title:"Boolean shape operations with Paper.js",paperjs:!0,setup:this.setup,draw:this.draw,onMouseMove:this.onMouseMove},r.createElement("br",null),o.map(function(t){var n=e.state.mode===t?"selected":null;return r.createElement("button",{className:n,key:t,onClick:function(){this.setMode(t)}.bind(e)},t)})))}});e.exports=s},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(223),o=r.createClass({displayName:"Projections",getDefaultProps:function(){return{title:"Projecting a point onto a Bézier curve"}},setup:function(e){e.setSize(320,320);var t=new e.Bezier([{x:248,y:188},{x:218,y:294},{x:45,y:290},{x:12,y:236},{x:14,y:82},{x:186,y:177},{x:221,y:90},{x:18,y:156},{x:34,y:57},{x:198,y:18}]);e.setCurve(t),e._lut=t.getLUT()},findClosest:function(e,t,n){var r,i,a=e.length,o=n(e[0],t),s=0;for(r=1;rt.w/2)){var i=Math.atan2(r,n);i<0&&(i=2*Math.PI+i);var a=t.curve.points,u=t.r,c=4*l(i/4)/3;a[1]={x:t.w/2+u,y:t.w/2+u*c},a[2]={x:t.w/2+t.r*(s(i)+c*o(i)),y:t.w/2+t.r*(o(i)-c*s(i))},a[3]={x:t.w/2+t.r*s(i),y:t.w/2+t.r*o(i)},t.setCurve(new t.Bezier(a)),t.angle=i}},drawCircle:function(e){e.setSize(325,325),e.reset();var t=e.getPanelWidth(),n=e.getPanelHeight(),r=60,i=t/2-r,a=.55228,o={x:-r/2,y:-r/4},s=new e.Bezier([{x:t/2+i,y:n/2},{x:t/2+i,y:n/2+a*i},{x:t/2+a*i,y:n/2+i},{x:t/2,y:n/2+i}]);e.setColor("lightgrey"),e.drawLine({x:0,y:n/2},{x:t+r,y:n/2},o),e.drawLine({x:t/2,y:0},{x:t/2,y:n+r},o);var l=s.points;e.setColor("red"),e.drawPoint(l[0],o),e.drawPoint(l[1],o),e.drawPoint(l[2],o),e.drawPoint(l[3],o),e.drawCurve(s,o),e.setColor("rgb(255,160,160)"),e.drawLine(l[0],l[1],o),e.drawLine(l[1],l[2],o),e.drawLine(l[2],l[3],o),e.setFill("red"),e.text(l[0].x-t/2+","+(l[0].y-n/2),{x:l[0].x+7,y:l[0].y+3},o),e.text(l[1].x-t/2+","+(l[1].y-n/2),{x:l[1].x+7,y:l[1].y+3},o),e.text(l[2].x-t/2+","+(l[2].y-n/2),{x:l[2].x+7,y:l[2].y+7},o),e.text(l[3].x-t/2+","+(l[3].y-n/2),{x:l[3].x,y:l[3].y+13},o),l.forEach(function(e){e.x=-(e.x-t)}),e.setColor("blue"),e.drawCurve(s,o),e.drawLine(l[2],l[3],o),e.drawPoint(l[2],o),e.setFill("blue"),e.text("reflected",{x:l[2].x-r/2,y:l[2].y+13},o),e.setColor("rgb(200,200,255)"),e.drawLine(l[1],l[0],o),e.drawPoint(l[1],o),l.forEach(function(e){e.y=-(e.y-n)}),e.setColor("green"),e.drawCurve(s,o),l.forEach(function(e){e.x=-(e.x-t)}),e.setColor("purple"),e.drawCurve(s,o),e.drawLine(l[1],l[0],o),e.drawPoint(l[1],o),e.setFill("purple"),e.text("reflected",{x:l[1].x+10,y:l[1].y+3},o),e.setColor("rgb(200,200,255)"),e.drawLine(l[2],l[3],o),e.drawPoint(l[2],o),e.setColor("black"),e.setFill("black"),e.drawLine({x:t/2,y:n/2},{x:t/2+i-2,y:n/2},o),e.drawLine({x:t/2,y:n/2},{x:t/2,y:n/2+i-2},o),e.text("r = "+i,{x:t/2+i/3,y:n/2+10},o)},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"In the previous section we tried to approximate a circular arc with a quadratic curve, and it mostly made us unhappy. Cubic curves are much better suited to this task, so what do we need to do?"),r.createElement("p",null,'For cubic curves, we basically want the curve to pass through three points on the circle: the start point, the mid point at "angle/2", and the end point at "angle". We then also need to make sure the control points are such that the start and end tangent lines line up with the circle\'s tangent lines at the start and end point.'),r.createElement("p",null,'The first thing we can do is "guess" what the curve should look like, based on the previously outlined curve-through-three-points procedure. This will give use a curve with correct start, mid and end points, but possibly incorrect derivatives at the start and end, because the control points might not be in the right spot. We can then slide the control points along the lines that connect them to their respective end point, until they effect the corrected derivative at the start and end points. However, if you look back at the section on fitting curves through three points, the rules used were such that they optimized for a near perfect hemisphere, so using the same guess won\'t be all that useful: guessing the solution based on knowing the solution is not really guessing.'),r.createElement("p",null,'So have a graphical look at a "bad" guess versus the true fit, where we\'ll be using the bad guess and the description in the second paragraph to derive the maths for the true fit:'),r.createElement(i,{preset:"arcfitting",title:"Cubic Bézier arc approximation",setup:this.setup,draw:this.draw,onMouseMove:this.onMouseMove}),r.createElement("p",null,'We see two curves here; in blue, our "guessed" curve and its control points, and in grey/black, the true curve fit, with proper control points that were shifted in, along line between our guessed control points, such that the derivatives at the start and end points are correct.'),r.createElement("p",null,'We can already seethat cubic curves are a lot better than quadratic curves, and don\'t look all that wrong until we go well past a quarter circle; ⅜th starts to hint at problems, and half a circle has an obvious "gap" between the real circle and the cubic approximation. Anything past that just looks plain ridiculous... but quarter curves actually look pretty okay!'),r.createElement("p",null,'So, maths time again: how okay is "okay"? Let\'s apply some more maths to find out.'),r.createElement("p",null,"Unlike for the quadratic curve, we can't use ",r.createElement("i",null,"t=0.5")," as our reference point because by its very nature it's one of the three points that are actually guaranteed to lie on the circular curve. Instead, we need a different ",r.createElement("i",null,"t")," value. If we run some analysis on the curve we find that the actual ",r.createElement("i",null,"t"),' value at which the curve is furthest from what it should be is 0.211325 (rounded), but we don\'t know "why", since finding this value involves root-finding, and is nearly impossible to do symbolically without pages and pages of math just to express one of the possible solutions.'),r.createElement("p",null,"So instead of walking you through the derivation for that value, let's simply take that ",r.createElement("i",null,"t")," value and see what the error is for circular arcs with an angle ranging from 0 to 2π:"),r.createElement("table",null,r.createElement("tbody",null,r.createElement("tr",null,r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-2pi.gif",height:"187px"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ 2π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-pi.gif",height:"187px"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-pi2.gif",height:"187px"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ ½π:"))))),r.createElement("p",null,"We see that cubic Bézier curves are much better when it comes to approximating circular arcs, with an error of less than 0.027 at the two \"bulge\" points for a quarter circle (which had an error of 0.06 for quadratic curves at the mid point), and an error near 0.001 for an eighth of a circle, so we're getting less than half the error for a quarter circle, or: at a slightly lower error, we're getting twice the arc. This makes cubic curves quite useful!"),r.createElement("p",null,'In fact, the precision of a cubic curve at a quarter circle is considered "good enough" by so many people that it\'s generally considered "just fine" to use four cubic Bézier curves to fake a full circle when no circle primitives are available; generally, people won\'t notice that it\'s not a real circle unless you also happen to overlay an actual circle, so that the difference becomes obvious.'),r.createElement("p",null,'So with the error analysis out of the way, how do we actually compute the coordinates needed to get that "true fit" cubic curve? The first observation is that we already know the start and end points, because they\'re the same as for the quadratic attempt:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ef34ab8f466ed3294895135a346b55ada05d779d.svg",style:{width:"13.275rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,"But we now need to find two control points, rather than one. If we want the derivatives at the start and end point to match the circle, then the first control point can only lie somewhere on the vertical line through S, and the second control point can only lie somewhere on the line tangent to point E, which means:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/4df65dae78bc5a0e6c5f23a2faae9a9d7a8b39b3.svg",style:{width:"8.325000000000001rem",height:"2.55015rem"}})),r.createElement("p",null,'where "a" is some scaling factor, and:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/cb32f8f9c3ae2b264a48003c237a798d02dc8935.svg",style:{width:"11.62485rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,'where "b" is also some scaling factor.'),r.createElement("p",null,"Starting with this information, we slowly maths our way to success, but I won't lie: the maths for this is pretty trig-heavy, and it's easy to get lost if you remember (or know!) some of the core trigonoetric identities, so if you just want to see the final result just skip past the next section!"),r.createElement("div",{className:"note"},r.createElement("h2",null,"Let's do this thing."),r.createElement("p",null,"Unlike for the quadratic case, we need some more information in order to compute ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"b"),", since they're no longer dependent variables. First, we observe that the curve is symmetrical, so whatever values we end up finding for C",r.createElement("sub",null,"1")," will apply to C",r.createElement("sub",null,"2")," as well (rotated along its tangent), so we'll focus on finding the location of C",r.createElement("sub",null,"1")," only. So here's where we do something that you might not expect: we're going to ignore for a moment, because we're going to have a much easier time if we just solve this problem with geometry first, then move to calculus to solve a much simpler problem."),r.createElement("p",null,"If we look at the triangle that is formed between our starting point, or initial guess C",r.createElement("sub",null,"1"),"and our real C",r.createElement("sub",null,"1"),", there's something funny going on: if we treat the line ","{","start,guess","}"," as our opposite side, the line ","{","guess,real","}"," as our adjacent side, with ","{","start,real","}"," our hypothenuse, then the angle for the corner hypothenuse/adjacent is half that of the arc we're covering. Try it: if you place the end point at a quarter circle (pi/2, or 90 degrees), the angle in our triangle is half a quarter (pi/4, or 45 degrees). With that knowledge, and a knowledge of what the length of any of our lines segments are (as a function), we can determine where our control points are, and thus have everything we need to find the error distance function. Of the three lines, the one we can easiest determine is ","{","start,guess","}",", so let's find out what the guessed control point is. Again geometrically, because we have the benefit of an on-curve ",r.createElement("i",null,"t=0.5")," value."),r.createElement("p",null,"The distance from our guessed point to the start point is exactly the same as the projection distance we looked at earlier. Using ",r.createElement("i",null,"t=0.5"),' as our point "B" in the "A,B,C" projection, then we know the length of the line segment ',"{","C,A","}",", since it's d",r.createElement("sub",null,"1")," = ","{","A,B","}"," + d",r.createElement("sub",null,"2")," = ","{","B,C","}",":"),r.createElement("p",null,r.createElement("img",{ className:"LaTeX SVG",src:"images/latex/b15a274c1e0a6aeeaf517b5d2c8ee0a7997dd617.svg",style:{width:"27.675rem",height:"2.32515rem"}})),r.createElement("p",null,"So that just leaves us to find the distance from ",r.createElement("i",null,"t=0.5")," to the baseline for an arbitrary angle φ, which is the distance from the centre of the circle to our ",r.createElement("i",null,"t=0.5")," point, minus the distance from the centre to the line that runs from start point to end point. The first is the same as the point P we found for the quadratic curve:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0b80423188012451e0400f473c19729eb2bad654.svg",style:{width:"13.350150000000001rem",height:"2.025rem"}})),r.createElement("p",null,"And the distance from the origin to the line start/end is another application of angles, since the triangle ","{","origin,start,C","}"," has known angles, and two known sides. We can find the length of the line ","{","origin,C","}",", which lets us trivially compute the coordinate for C:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/9be55fb38d5d30bbc6c7140afb1c7bc097bc044e.svg",style:{width:"18.675rem",height:"5.3248500000000005rem"}})),r.createElement("p",null,"With the coordinate C, and knowledge of coordinate B, we can determine coordinate A, and get a vector that is identical to the vector ","{","start,guess","}",":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/262f2eca63105779f30a0a5445cf76f60786039a.svg",style:{width:"27.675rem",height:"3.67515rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0e83ebbac13a84ef6036bf4be57b3d1b6cb316f8.svg",style:{width:"14.99985rem",height:"3.29985rem"}})),r.createElement("p",null,"Which means we can now determine the distance ","{","start,guessed","}",", which is the same as the distance","{","C,A","}",", and use that to determine the vertical distance from our start point to our C",r.createElement("sub",null,"1"),":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c87e454fb11ef7f15c7386e83ca1ce41a004d8a7.svg",style:{width:"17.850150000000003rem",height:"4.64985rem"}})),r.createElement("p",null,"And after this tedious detour to find the coordinate for C",r.createElement("sub",null,"1"),", we can find C",r.createElement("sub",null,"2")," fairly simply, since it's lies at distance -C",r.createElement("sub",null,"1y")," along the end point's tangent:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/25f027074b6af8ca7b640e27636e3bf89c28afdb.svg",style:{width:"36.675000000000004rem",height:"6.89985rem"}})),r.createElement("p",null,"And that's it, we have all four points now for an approximation of an arbitrary circular arc with angle φ.")),r.createElement("p",null,"So, to recap, given an angle φ, the new control coordinates are:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c4d82e44d1c67dda8ba26aa6da0f406d05eba618.svg",style:{width:"15.075000000000001rem",height:"2.55015rem"}})),r.createElement("p",null,"and"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3a4b1ee00eebb7697e5513ef9df673928913252e.svg",style:{width:"23.02515rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,'And, because the "quarter curve" special case comes up so incredibly often, let\'s look at what these new control points mean for the curve coordinates of a quarter curve, by simply filling in φ = π/2:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/63e0936b4849d4cdbb9a2e0909181259be951e4d.svg",style:{width:"28.65015rem",height:"1.94985rem"}})),r.createElement("p",null,"Which, in decimal values, rounded to six significant digits, is:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/fd12e65204a31319b66355c6ff99e6b3d9603b05.svg",style:{width:"28.65015rem",height:"1.125rem"}})),r.createElement("p",null,"Of course, this is for a circle with radius 1, so if you have a different radius circle, simply multiply the coordinate by the radius you need. And then finally, forming a full curve is now a simple a matter of mirroring these coordinates about the origin:"),r.createElement(i,{preset:"simple",title:"Cubic Bézier circle approximation",draw:this.drawCircle,"static":!0}))}});e.exports=u},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(223),o=n(226),s=Math.atan2,l=Math.PI,u=2*l,c=Math.cos,h=Math.sin,d=r.createClass({displayName:"Introduction",statics:{keyHandlingOptions:{propName:"error",values:{38:.1,40:-.1},controller:function(e){e.error<.1&&(e.error=.1)}}},getDefaultProps:function(){return{title:"Approximating Bézier curves with circular arcs"}},setupCircle:function(e){var t=new e.Bezier(70,70,140,40,240,130);e.setCurve(t)},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.error=.5},getCCenter:function(e,t,n,r){var i,a=n.x-t.x,o=n.y-t.y,d=r.x-n.x,p=r.y-n.y,f=a*c(l/2)-o*h(l/2),m=a*h(l/2)+o*c(l/2),g=d*c(l/2)-p*h(l/2),v=d*h(l/2)+p*c(l/2),y=(t.x+n.x)/2,w=(t.y+n.y)/2,b=(n.x+r.x)/2,_=(n.y+r.y)/2,x=y+f,E=w+m,C=b+g,k=_+v,N=e.utils.lli8(y,w,x,E,b,_,C,k),S=e.utils.dist(N,t),P=s(t.y-N.y,t.x-N.x),D=s(n.y-N.y,n.x-N.x),O=s(r.y-N.y,r.x-N.x);return PD||D>O)&&(P+=u),P>O&&(i=O,O=P,P=i)):O s + L - order; i--) ","{","\n"," let numerator = t - knots[i]","\n"," let denominator = knots[i - L + order] - knots[i]","\n"," let alpha = numerator / denominator","\n"," let v[i] = alpha * v[i] + (1-alpha) * v[i-1]","\n"," ","}","\n"," ","}"),r.createElement("p",null,'(A nice bit of behaviour in this code is that we work the interpolation "backwards", starting at ',r.createElement("code",null,"i=s")," at each level of the interpolation, and we stop when ",r.createElement("code",null,"i = s - order + level"),", so we always end up with a value for ",r.createElement("code",null,"i")," such that those ",r.createElement("code",null,"v[i-1]")," don't try to use an array index that doesn't exist)"),r.createElement("h2",null,"Open vs. closed paths"),r.createElement("p",null,"Much like poly-Béziers, B-Splines can be either open, running from the first point to the last point, or closed, where the first and last point are ",r.createElement("em",null,"the same point"),". However, because B-Splines are an interpolation of curves, not just point, we can't simply make the first and last point the same, we need to link a few point point: for an order ",r.createElement("code",null,"d")," B-Spline, we need to make the last ",r.createElement("code",null,"d")," point the same as the first ",r.createElement("code",null,"d")," points. And the easiest way to do this is to simply append ",r.createElement("code",null,"points.splice(0,d)")," to ",r.createElement("code",null,"points"),". Done!"),r.createElement("p",null,'Of course if we want to manipulate these kind of curves we need to make sure to mark them as "closed" so that we know the coordinate for ',r.createElement("code",null,"points[0]")," and ",r.createElement("code",null,"points[n-k]")," etc. are the same coordinate, and manipulating one will equally manipulate the other, but programming generally makes this really easy by storing references to coordinates (or other linked values such as coordinate weights, discussed in the NURBS section) rather than separate coordinate objects."),r.createElement("h2",null,"Manipulating the curve through the knot vector"),r.createElement("p",null,"The most important thing to understand when it comes to B-Splines is that they work ",r.createElement("em",null,"because"),' of the concept of a knot vector. As mentioned above, knots represent "where individual control points start/stop influencing the curve", but we never looked at the ',r.createElement("em",null,"values")," that go in the knot vector. If you look back at the N() and a() functions, you see that interpolations are based on intervals in the knot vector, rather than the actual values in the knot vector, and we can exploit this to do some pretty interesting things with clever manipulation of the knot vector. Specifically there are four things we can do that are worth looking at:"),r.createElement("ol",null,r.createElement("li",null,"we can use a uniform knot vector, with equally spaced intervals,"),r.createElement("li",null,"we can use a non-uniform knot vector, without enforcing equally spaced internvals,"),r.createElement("li",null,'we can collapse sequential knots to the same value, locally lowering curve complexity using "null" intervals, and'),r.createElement("li",null,"we can form a special case non-uniform vector, by combining (1) and (3) to for a vector with collapsed start and end knots, with a uniform vector in between.")),r.createElement("h3",null,"Uniform B-Splines"),r.createElement("p",null,"The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines ",r.createElement("em",null,"the same intervals"),", or even [0,2,3,...,18,20,22], which also defines ",r.createElement("em",null,"the same intervals"),", just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature."),r.createElement("div",{ -className:"two-column"},r.createElement(o,{ref:"uniform-spline"}),r.createElement(i,{sketch:n(270),controller:function(t,n){return e.bindKnots(t,n,"uniform-spline")}})),r.createElement("p",null,"This is an important point: the intervals that the knot vector defines are ",r.createElement("em",null,"relative")," intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve."),r.createElement("p",null,"The problem with uniform knot vectors is that, as we need ",r.createElement("code",null,"order"),' control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead...'),r.createElement("h3",null,"Reducing local curve complexity by collapsing intervals"),r.createElement("p",null,"By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for ever interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing ",r.createElement("code",null,"order"),' knots creates a situation where all continuity is lost and the curve "kinks".'),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"center-cut-bspline"}),r.createElement(i,{sketch:n(271),controller:function(t,n){return e.bindKnots(t,n,"center-cut-bspline")}})),r.createElement("h3",null,"Open-Uniform B-Splines"),r.createElement("p",null,"By combining knot interval collapsing at the start and end of the curve, with uniform knots in between, we can overcome the problem of the curve not starting and ending where we'd kind of like it to:"),r.createElement("p",null,"For any curve of degree ",r.createElement("code",null,"D")," with control points ",r.createElement("code",null,"N"),", we can define a knot vector of length ",r.createElement("code",null,"N+D+1")," in which the values ",r.createElement("code",null,"0 ... D+1")," are the same, the values ",r.createElement("code",null,"D+1 ... N+1"),' follow the "uniform" pattern, and the values ',r.createElement("code",null,"N+1 ... N+D+1"),' are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape.'),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"open-uniform-bspline"}),r.createElement(i,{sketch:n(272),controller:function(t,n){return e.bindKnots(t,n,"open-uniform-bspline")}})),r.createElement("h3",null,"Non-uniform B-Splines"),r.createElement("p",null,'This is essentialy the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value ',r.createElement("code",null,"knots[k+1]"),"should be equal to, or greater than ",r.createElement("code",null,"knots[k]"),"."),r.createElement("h2",null,"One last thing: Rational B-Splines"),r.createElement("p",null,'While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that\'s "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point.'),r.createElement("div",{className:"two-column"},r.createElement(s,{ref:"rational-uniform-bspline-weights"}),r.createElement(i,{scrolling:!0,sketch:n(273),controller:function(t,n,r,i){e.bindWeights(t,r,i,"rational-uniform-bspline-weights")}})),r.createElement("p",null,'Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.'),r.createElement("p",null,"While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last."),r.createElement("h2",null,"Extending our implementation to cover rational splines"),r.createElement("p",null,"The algorithm for working with Rational B-Splines is virtually identical to the regular algorithm, and the extension to work in the control point weights is fairly simple: we extend each control point from a point in its original number of dimensions (2D, 3D, etc) to one dimension higher, scaling the original dimensions by the control point's weight, and then assigning that weight as its value for the extended dimension."),r.createElement("p",null,"For example, a 2D point ",r.createElement("code",null,"(x,y)")," with weight ",r.createElement("code",null,"w")," becomes a 3D point ",r.createElement("code",null,"(w * x, w * y, w)"),"."),r.createElement("p",null,"We then run the same algorithm as before, which will automaticall perform weight interpolation in addition to regular coordinate interpolation, because all we've done is pretended we have coordinates in a higher dimension. The algorithm doesn't really care about how many dimensions it needs to interpolate."),r.createElement("p",null,'In order to recover our "real" curve point, we take the final result of the point generation algorithm, and "unweigh" it: we take the final point\'s derived weight ',r.createElement("code",null,"w'")," and divide all the regular coordinate dimensions by it, then throw away the weight information."),r.createElement("p",null,"Based on our previous example, we take the final 3D point ",r.createElement("code",null,"(x', y', w')"),", which we then turn back into a 2D point by computing ",r.createElement("code",null,"(x'/w', y'/w')"),". And that's it, we're done!"))}});e.exports=l},function(e,t,n){"use strict";var r=n(2),i=n(265),a=r.createClass({displayName:"BSplineGraphic",componentWillMount:function(){var e=this;this.cvs=void 0,this.ctx=void 0,this.key=void 0,this.keyCode=void 0,this.mouseX=void 0,this.mouseY=void 0,this.isMouseDown=void 0,this.width=0,this.height=0,this.activeDistance=9,this.points=[],this.knots=[],this.weights=[],this.nodes=[],this.cp=void 0,this.dx=void 0,this.dy=void 0;var t=this.props.sketch;Object.keys(t).forEach(function(n){e[n]=t[n],"function"==typeof e[n]&&(e[n]=e[n].bind(e))})},render:function(){return r.createElement("canvas",{className:"bspline-graphic",ref:"sketch"})},keydownlisten:function(e){this.setKeyboardValues(e),this.keyDown()},keyuplisten:function(e){this.setKeyboardValues(e),this.keyUp()},keypresslisten:function(e){this.setKeyboardValues(e),this.keyPressed()},mousedownlisten:function(e){this.setMouseValues(e),this.mouseDown()},mouseuplisten:function(e){this.setMouseValues(e),this.mouseUp()},mousemovelisten:function(e){this.setMouseValues(e),this.mouseMove(),this.isMouseDown&&this.mouseDrag&&this.mouseDrag()},wheellissten:function(e){e.preventDefault(),this.scrolled(e.deltaY<0?1:-1)},componentDidMount:function(){var e=this.cvs=this.refs.sketch;e.addEventListener("keydown",this.keydownlisten),e.addEventListener("keyup",this.keyuplisten),e.addEventListener("keypress",this.keypresslisten),e.addEventListener("mousedown",this.mousedownlisten),e.addEventListener("mouseup",this.mouseuplisten),e.addEventListener("mousemove",this.mousemovelisten),this.props.scrolling&&e.addEventListener("wheel",this.wheellissten),this.setup()},componentWillUnmount:function(){var e=this.cvs=this.refs.sketch;e.removeEventListener("keydown",this.keydownlisten),e.removeEventListener("keyup",this.keyuplisten),e.removeEventListener("keypress",this.keypresslisten),e.removeEventListener("mousedown",this.mousedownlisten),e.removeEventListener("mouseup",this.mouseuplisten),e.removeEventListener("mousemove",this.mousemovelisten),this.props.scrolling&&e.removeEventListener("wheel",this.wheellissten)},drawCurve:function(e){e=e||this.points;var t=this.ctx,n=this.weights.length>0&&this.weights;t.beginPath();var r=i(0,this.degree,e,this.knots,n);t.moveTo(r[0],r[1]);for(var a=.01;a<1;a+=.01)r=i(a,this.degree,e,this.knots,n),t.lineTo(r[0],r[1]);r=i(1,this.degree,e,this.knots,n),t.lineTo(r[0],r[1]),t.stroke(),t.closePath()},drawKnots:function(e){var t=this,n=this.knots,r=this.weights.length>0&&this.weights;n.forEach(function(a,o){if(!(on.length-1-t.degree)){var s=i(a,t.degree,e,n,r,!1,!0);t.circle(s[0],s[1],3)}})},drawNodes:function(e){var t,n=this;this.stroke(150),this.nodes.forEach(function(r,a){try{t=i(r,n.degree,e,n.knots,!1,!1,!0),n.line(t[0],t[1],e[a][0],e[a++][1])}catch(o){console.error(o)}})},formKnots:function(e,t){if(t=t===!0,!t)return this.formUniformKnots(e);var n,r=e.length,i=[],a=r-this.degree;for(n=1;n=0;n--)t.push(n);return t.reverse()},formNodes:function(e,t){var n,r,i,a=[this.degree,e.length-1-this.degree],o=[];for(r=0;re[a[1]]||o.push(n)}return o},formWeights:function(e){var t=[];return e.forEach(function(e){return t.push(1)}),t},setDegree:function(e){this.degree+=e,this.knots=this.formKnots(this.points),this.nodes=this.formNodes(this.knots,this.points)},near:function(e,t,n){var r=e.x-t,i=e.y-n,a=Math.sqrt(r*r+i*i);return a1&&this.setDegree(-1),this.redraw()},keyUp:function(){},keyPressed:function(){},mouseDown:function(){this.isMouseDown=!0,this.cp=this.getCurrentPoint(this.mouseX,this.mouseY),this.cp||(this.points.push({x:this.mouseX,y:this.mouseY}),this.knots=this.formKnots(this.points),this.nodes=this.formNodes(this.knots,this.points)),this.redraw()},mouseUp:function(){this.isMouseDown=!1,this.cp=!1,this.redraw()},mouseDrag:function(){this.cp&&(this.cp.x=this.mouseX,this.cp.y=this.mouseY,this.redraw())},mouseMove:function(){},scrolled:function(e){if(this.cp=this.getCurrentPoint(this.mouseX,this.mouseY),this.cp){var t=this.points.indexOf(this.cp);this.weights.length>t&&(this.weights[t]+=.1*e,this.weights[t]<0&&(this.weights[t]=0)),t=this.points.indexOf(this.cp,t+1),t!==-1&&this.weights.length>t&&(this.weights[t]+=.1*e,this.weights[t]<0&&(this.weights[t]=0)),this.redraw()}},setKeyboardValues:function(e){e.ctrlKey||e.metaKey||e.altKey||e.preventDefault(),this.key=e.key,this.keyCode=e.code},setMouseValues:function(e){var t=this.cvs.getBoundingClientRect();this.mouseX=e.clientX-t.left,this.mouseY=e.clientY-t.top},size:function(e,t){this.width=0|e,this.height=0|(t||e),this.cvs.width=this.width,this.cvs.height=this.height,this.ctx=this.cvs.getContext("2d")},redraw:function(){this.draw()},clear:function(){this.ctx.clearRect(0,0,this.width,this.height)},grid:function(e){e=(0|(e||10))+.5,this.stroke(200,200,220);for(var t=e;th-1)throw new Error("degree must be less than or equal to point count - 1");if(!i)for(i=[],s=0;sm)throw new Error("out of bounds");for(u=p[0];u=r[u]&&e<=r[u+1]);u++);var g=[];for(s=0;su-t-1+c;s--)for(v=(e-r[s])/(r[s+t+1-c]-r[s]),l=0;l=s)return null;var c={type:t,min:n,max:i,step:a,value:l,onChange:function(t){var n=e.state.weights;n[u]=t.target.value,o&&u0&&this.weights;t.beginPath();var r=i(0,this.degree,e,this.knots,n);t.moveTo(r[0],r[1]);for(var a=.01;a<1;a+=.01)r=i(a,this.degree,e,this.knots,n),t.lineTo(r[0],r[1]);r=i(1,this.degree,e,this.knots,n),t.lineTo(r[0],r[1]),t.stroke(),t.closePath()},drawKnots:function(e){var t=this,n=this.knots,r=this.weights.length>0&&this.weights;n.forEach(function(a,o){if(!(on.length-1-t.degree)){var s=i(a,t.degree,e,n,r,!1,!0);t.circle(s[0],s[1],3)}})},drawNodes:function(e){var t,n=this;this.stroke(150),this.nodes.forEach(function(r,a){try{t=i(r,n.degree,e,n.knots,!1,!1,!0),n.line(t[0],t[1],e[a][0],e[a++][1])}catch(o){console.error(o)}})},formKnots:function(e,t){if(t=t===!0,!t)return this.formUniformKnots(e);var n,r=e.length,i=[],a=r-this.degree;for(n=1;n=0;n--)t.push(n);return t.reverse()},formNodes:function(e,t){var n,r,i,a=[this.degree,e.length-1-this.degree],o=[];for(r=0;re[a[1]]||o.push(n)}return o},formWeights:function(e){var t=[];return e.forEach(function(e){return t.push(1)}),t},setDegree:function(e){this.degree+=e,this.knots=this.formKnots(this.points),this.nodes=this.formNodes(this.knots,this.points)},near:function(e,t,n){var r=e.x-t,i=e.y-n,a=Math.sqrt(r*r+i*i);return a1&&this.setDegree(-1),this.redraw()},keyUp:function(){},keyPressed:function(){},mouseDown:function(){this.isMouseDown=!0,this.cp=this.getCurrentPoint(this.mouseX,this.mouseY),this.cp||(this.points.push({x:this.mouseX,y:this.mouseY}),this.knots=this.formKnots(this.points),this.nodes=this.formNodes(this.knots,this.points)),this.redraw()},mouseUp:function(){this.isMouseDown=!1,this.cp=!1,this.redraw()},mouseDrag:function(){this.cp&&(this.cp.x=this.mouseX,this.cp.y=this.mouseY,this.redraw())},mouseMove:function(){},scrolled:function(e){if(this.cp=this.getCurrentPoint(this.mouseX,this.mouseY),this.cp){var t=this.points.indexOf(this.cp);this.weights.length>t&&(this.weights[t]+=.1*e,this.weights[t]<0&&(this.weights[t]=0)),t=this.points.indexOf(this.cp,t+1),t!==-1&&this.weights.length>t&&(this.weights[t]+=.1*e,this.weights[t]<0&&(this.weights[t]=0)),this.redraw()}},setKeyboardValues:function(e){e.ctrlKey||e.metaKey||e.altKey||e.preventDefault(),this.key=e.key,this.keyCode=e.code},setMouseValues:function(e){var t=this.cvs.getBoundingClientRect();this.mouseX=e.clientX-t.left,this.mouseY=e.clientY-t.top},size:function(e,t){this.width=0|e,this.height=0|(t||e),this.cvs.width=this.width,this.cvs.height=this.height,this.ctx=this.cvs.getContext("2d")},redraw:function(){this.draw()},clear:function(){this.ctx.clearRect(0,0,this.width,this.height)},grid:function(e){e=(0|(e||10))+.5,this.stroke(200,200,220);for(var t=e;th-1)throw new Error("degree must be less than or equal to point count - 1");if(!i)for(i=[],s=0;sm)throw new Error("out of bounds");for(u=p[0];u=r[u]&&e<=r[u+1]);u++);var g=[];for(s=0;su-t-1+c;s--)for(v=(e-r[s])/(r[s+t+1-c]-r[s]),l=0;l=s)return null;var c={type:t,min:n,max:i,step:a,value:l,onChange:function(t){var n=e.state.weights;n[u]=t.target.value,o&&uComments and questions

If you enjoyed this book, or you simply found it useful for something you were trying to - get done, and you were wondering how to let me know you appreciated this book, you can always - buy me a coffee, however much a coffee is where you live. This work has grown over the years, from a small primer to a 70ish print-page-equivalent reader on the subject of Bézier curves, and a lot of coffee went into the making of it. I don't regret a minute I spent on writing it, but I can always do with some more coffee to keep on writing!

- +
);