(function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.BezierArticle=t():e.BezierArticle=t()})(window,function(){var e=Math.log,n=Math.floor,t=Math.tan,o=Math.round,w=Math.max,d=Math.min,l=Math.PI,r=Math.pow,u=Math.sqrt,h=Math.atan2,m=Math.acos,s=Math.sin,g=Math.cos,_=Math.abs,a=String.fromCharCode;return function(e){function t(a){if(n[a])return n[a].exports;var i=n[a]={i:a,l:!1,exports:{}};return e[a].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,a){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:a})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(t.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var i in e)t.d(a,i,function(t){return e[t]}.bind(null,i));return a},t.n=function(e){var n=e&&e.__esModule?function(){return e["default"]}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=315)}([function(e,t,n){"use strict";var a=n(6),i=n(56),r=new i;e.exports=function(e,t){var n={getDefaultProps:function(){return{page:e,title:r.getTitle(e),handler:t}},render:function(){return r.getContent(e,this)}};return t&&Object.keys(t).forEach(function(e){n[e]=t[e]}),a.createClass(n)}},function(e){"use strict";var t=function(){};!1,e.exports=function(n,i,r,a,o,s,d,e){if(t(i),!n){var l;if(void 0===i)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,a,o,s,d,e],u=0;l=new Error(i.replace(/%s/g,function(){return c[u++]})),l.name="Invariant Violation"}throw l.framesToPop=1,l}}},function(e){"use strict";e.exports=function(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,a=0;an;n++)t["_"+a(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"].forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}()?Object.assign:function(e){for(var a=t(e),o=1,d,l;o=m.hasBooleanValue+m.hasNumericValue+m.hasOverloadedBooleanValue||!1?void 0:i("50",u),!1,s.hasOwnProperty(u)){var g=s[u];m.attributeName=g,!1}r.hasOwnProperty(u)&&(m.attributeNamespace=r[u]),l.hasOwnProperty(u)&&(m.propertyName=l[u]),c.hasOwnProperty(u)&&(m.mutationMethod=c[u]),d.properties[u]=m}}},s=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",d={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:s,ATTRIBUTE_NAME_CHAR:s+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0,n;t]/;e.exports=function(e){return"boolean"==typeof e||"number"==typeof e?""+e:t(e)}},function(e,t,n){"use strict";var a=n(7),i=n(42),r=/^[ \r\n\t\f]/,o=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,s=n(41),d=s(function(e,t){if(e.namespaceURI===i.svg&&!("innerHTML"in e)){l=l||document.createElement("div"),l.innerHTML=""+t+"";for(var n=l.firstChild;n.firstChild;)e.appendChild(n.firstChild)}else e.innerHTML=t}),l;if(a.canUseDOM){var c=document.createElement("div");c.innerHTML=" ",""===c.innerHTML&&(d=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&o.test(t)){e.innerHTML="\uFEFF"+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t}),c=null}e.exports=d},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(21),r=n(75),o=n(44);i.augmentClass(a,{screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:o,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+r.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+r.currentScrollTop}}),e.exports=a},function(e,t,n){"use strict";var r=n(2),a=n(1),o={};e.exports={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(t,n,i,a,o,s,d,e){this.isInTransaction()&&1?r("27"):void 0;var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=t.call(n,i,a,o,s,d,e),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(e){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e,a;nn;n++)t["_"+a(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"].forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}()?Object.assign:function(e){for(var a=t(e),o=1,d,l;oa.length?n+" (keys: "+a.join(", ")+")":n}function r(e){var t=d.get(e);if(!t){return null}return!1,t}var o=n(2),s=n(13),d=n(20),l=n(8),c=n(9),u=n(1),h=n(3),p={isMounted:function(e){var t=d.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){p.validateCallback(t,n);var i=r(e);return i?void(i._pendingCallbacks?i._pendingCallbacks.push(t):i._pendingCallbacks=[t],a(i)):null},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],a(e)},enqueueForceUpdate:function(e){var t=r(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,a(t))},enqueueReplaceState:function(e,t,n){var i=r(e,"replaceState");i&&(i._pendingStateQueue=[t],i._pendingReplaceState=!0,n!==void 0&&null!==n&&(p.validateCallback(n,"replaceState"),i._pendingCallbacks?i._pendingCallbacks.push(n):i._pendingCallbacks=[n]),a(i))},enqueueSetState:function(e,t){var n=r(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),a(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,a(e)},validateCallback:function(e,t){e&&"function"!=typeof e&&1?o("122",t,i(e)):void 0}};e.exports=p},function(e){"use strict";e.exports={escape:function(e){var t=/[=:]/g,n={"=":"=0",":":"=2"},a=(""+e).replace(t,function(e){return n[e]});return"$"+a},unescape:function(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"},a="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+a).replace(t,function(e){return n[e]})}}},function(e){"use strict";e.exports=function(e,t){var n=null===e||!1===e,a=null===t||!1===t;if(n||a)return n===a;var i=typeof e,r=typeof t;return"string"==i||"number"==i?"string"===r||"number"===r:"object"===r&&e.type===t.type&&e.key===t.key}},function(e){"use strict";function t(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!==e&&t!==t}var n=Object.prototype.hasOwnProperty;e.exports=function(e,a){if(t(e,a))return!0;if("object"!=typeof e||null===e||"object"!=typeof a||null===a)return!1;var r=Object.keys(e),o=Object.keys(a);if(r.length!==o.length)return!1;for(var s=0;se.map(e=>e[n]))}},function(e){e.exports=function(t){if(t.length!==t[0].length)return void console.log("not square");var n=0,a=0,r=0,o=t.length,s=0,d=[],l=[];for(n=0;ne?-a(-e,1/3):a(e,1/3)},c=l,y=2*c,p=c/2,v=Number.MAX_SAFE_INTEGER||9007199254740991,b=Number.MIN_SAFE_INTEGER||-9007199254740991,x={x:0,y:0,z:0},E={Tvalues:[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues:[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],arcfn:function(e,t){var n=t(e),a=n.x*n.x+n.y*n.y;return"undefined"!=typeof n.z&&(a+=n.z*n.z),f(a)},compute:function(e,t,n){if(0===e)return t[0];let r=t.length-1;if(1===e)return t[r];var o=t,s=1-e;if(0==r)return t[0];if(1==r)return w={x:s*o[0].x+e*o[1].x,y:s*o[0].y+e*o[1].y},n&&(w.z=s*o[0].z+e*o[1].z),w;if(4>r){var l=s*s,u=e*e,h=0,m,g,f;2==r?(o=[o[0],o[1],o[2],x],m=l,g=2*(s*e),f=u):3==r&&(m=l*s,g=3*(l*e),f=3*(s*u),h=e*u);var w={x:m*o[0].x+g*o[1].x+f*o[2].x+h*o[3].x,y:m*o[0].y+g*o[1].y+f*o[2].y+h*o[3].y};return n&&(w.z=m*o[0].z+g*o[1].z+f*o[2].z+h*o[3].z),w}for(var y=JSON.parse(JSON.stringify(t));1r.x.min&&(t=r.x.min),n>r.y.min&&(n=r.y.min),ao&&(o=d[n]);return{min:r,mid:(r+o)/2,max:o,size:o-r}},align:function(e,n){var r=n.p1.x,o=n.p1.y,s=-d(n.p2.y-o,n.p2.x-r);return e.map(function(e){return{x:(e.x-r)*i(s)-(e.y-o)*t(s),y:(e.x-r)*t(s)+(e.y-o)*i(s)}})},roots:function(e,n){n=n||{p1:{x:0,y:0},p2:{x:1,y:0}};var o=e.length-1,s=E.align(e,n),l=function(e){return 0<=e&&1>=e};if(2==o){var u=s[0].y,h=s[1].y,g=s[2].y,v=u-2*h+g;if(0!==v){var x=-f(h*h-u*g),_=-u+h,C=-(x+_)/v,k=-(-x+_)/v;return[C,k].filter(l)}return h!==g&&0===v?[(2*h-g)/(2*h-2*g)].filter(l):[]}var S=s[0].y,T=s[1].y,N=s[2].y,P=s[3].y,v=-S+3*T-3*N+P,u=3*S-6*T+3*N,h=-3*S+3*T,g=S;if(E.approximately(v,0)){if(E.approximately(u,0))return E.approximately(h,0)?[]:[-g/h].filter(l);var L=f(h*h-4*u*g),I=2*u;return[(L-h)/I,(-h-L)/I].filter(l)}u/=v,h/=v,g/=v;var s=(3*h-u*u)/3,z=s/3,L=(2*u*u*u-9*u*h+27*g)/27,B=L/2,A=B*B+z*z*z,M,C,D,O,R;if(0>A){var j=-s/3,F=f(j*j*j),r=-L/(2*F),t=-1>r?-1:1B?w(-B):-w(B),D=2*M-u/3,O=-M-u/3,[D,O].filter(l);var G=f(A);return M=w(-B+G),C=w(B+G),[M-C-u/3].filter(l)},droots:function(e){if(3===e.length){var t=e[0],n=e[1],i=e[2],r=t-2*n+i;if(0!==r){var o=-f(n*n-t*i),s=-t+n;return[-(o+s)/r,-(-o+s)/r]}return n!==i&&0===r?[(2*n-i)/(2*(n-i))]:[]}if(2===e.length){var t=e[0],n=e[1];return t===n?[]:[t/(t-n)]}},curvature:function(e,t,n,i){var s=E.derive(t),l=s[0],c=s[1],u=0,h=0,p=E.compute(e,l),d=E.compute(e,c),m=p.x*p.x+p.y*p.y,g,w,y,v;if(n?(g=f(a(p.y*d.z-d.y*p.z,2)+a(p.z*d.x-d.z*p.x,2)+a(p.x*d.y-d.x*p.y,2)),w=a(m+p.z*p.z,2/3)):(g=p.x*d.y-p.y*d.x,w=a(m,2/3)),0===g||0===w)return{k:0,r:0};if(u=g/w,h=w/g,!i){var b=E.curvature(e-.001,t,n,!0).k,x=E.curvature(e+.001,t,n,!0).k;v=(x-u+(u-b))/2,y=(o(x-u)+o(u-b))/2}return{k:u,r:h,dk:v,adk:y}},inflections:function(e){if(4>e.length)return[];var n=E.align(e,{p1:e[0],p2:e.slice(-1)[0]}),i=n[2].x*n[1].y,a=n[3].x*n[1].y,r=n[1].x*n[2].y,o=n[3].x*n[2].y,s=18*(-3*i+2*a+3*r-o),l=18*(3*i-a-3*r),c=18*(r-i);if(E.approximately(s,0)){if(!E.approximately(l,0)){var h=-c/l;if(0<=h&&1>=h)return[h]}return[]}var t=u(l*l-4*s*c),o=2*s;return E.approximately(o,0)?[]:[(t-l)/o,-(l+t)/o].filter(function(e){return 0<=e&&1>=e})},bboxoverlap:function(e,n){var a=["x","y"],r=a.length,s,c,u,h,p;for(s=0;s=p)return!1;return!0},expandbox:function(e,t){t.x.mine.x.max&&(e.x.max=t.x.max),t.y.max>e.y.max&&(e.y.max=t.y.max),t.z&&t.z.max>e.z.max&&(e.z.max=t.z.max),e.x.mid=(e.x.min+e.x.max)/2,e.y.mid=(e.y.min+e.y.max)/2,e.z&&(e.z.mid=(e.z.min+e.z.max)/2),e.x.size=e.x.max-e.x.min,e.y.size=e.y.max-e.y.min,e.z&&(e.z.size=e.z.max-e.z.min)},pairiteration:function(e,t,n){var a=e.bbox(),i=t.bbox(),r=n||.5;if(a.x.size+a.y.sizeN||N>m)&&(r+=y),r>m&&(P=m,m=r,r=P)):m=e}),n=n.concat(t[e].sort(f.numberSort))}.bind(this)),n=n.sort(f.numberSort).filter(function(e,t){return n.indexOf(e)===t}),t.values=n,t},bbox:function(){var e=this.extrema(),t={};return this.dims.forEach(function(n){t[n]=f.getminmax(this,n,e[n])}.bind(this)),t},overlaps:function(e){var t=this.bbox(),n=e.bbox();return f.bboxoverlap(t,n)},offset:function(e,t){if("undefined"!=typeof t){var a=this.get(e),i=this.normal(e),n={c:a,n:i,x:a.x+i.x*t,y:a.y+i.y*t};return this._3d&&(n.z=a.z+i.z*t),n}if(this._linear){var r=this.normal(0),o=this.points.map(function(t){var n={x:t.x+e*r.x,y:t.y+e*r.y};return t.z&&i.z&&(n.z=t.z+e*r.z),n});return[new y(o)]}var s=this.reduce();return s.map(function(t){return t.scale(e)})},simple:function(){if(3===this.order){var e=f.angle(this.points[0],this.points[3],this.points[1]),n=f.angle(this.points[0],this.points[3],this.points[2]);if(0n||0>e&&0=n;)for(n=e+a;n<=1+a;n+=a)if(l=i.split(e,n),!l.simple()){if(n-=a,t(e-n)e&&(l=i.split(e,1),l._t1=f.map(e,0,1,i._t1,i._t2),l._t2=i._t2,o.push(l))}),o},scale:function(e){var n=this.order,a=!1;if("function"==typeof e&&(a=e),a&&2===n)return this.raise().scale(a);var i=this.clockwise,r=a?a(0):e,s=a?a(1):e,d=[this.offset(0,10),this.offset(1,10)],l=f.lli4(d[0],d[0].c,d[1],d[1].c);if(!l)throw new Error("cannot scale this curve. Try reducing it first.");var o=this.points,c=[];return([0,1].forEach(function(e){var t=c[e*n]=f.copy(o[e*n]);t.x+=(e?s:r)*d[e].n.x,t.y+=(e?s:r)*d[e].n.y}.bind(this)),!a)?([0,1].forEach(function(e){if(2!==this.order||!e){var t=c[e*n],a=this.derivative(e),i={x:t.x+a.x,y:t.y+a.y};c[e+1]=f.lli4(t,i,l,o[e+1])}}.bind(this)),new y(c)):([0,1].forEach(function(r){if(2!==this.order||!r){var t=o[r+1],s={x:t.x-l.x,y:t.y-l.y},d=a?a((r+1)/n):e;a&&!i&&(d=-d);var u=h(s.x*s.x+s.y*s.y);s.x/=u,s.y/=u,c[r+1]={x:t.x+d*s.x,y:t.y+d*s.y}}}.bind(this)),new y(c))},outline:function(e,t,n,a){function i(t,n,e,a,i){return function(r){var o=n-t;return f.map(r,0,1,t+a/e*o,t+(a+i)/e*o)}}t="undefined"==typeof t?e:t;var r=this.reduce(),o=r.length,s=[],d=[],l=0,u=this.length(),h;r.forEach(function(r){_=r.length(),"undefined"!=typeof n&&"undefined"!=typeof a?(s.push(r.scale(i(e,n,u,l,_))),d.push(r.scale(i(-t,-a,u,l,_)))):(s.push(r.scale(e)),d.push(r.scale(-t))),l+=_}),d=d.map(function(e){return h=e.points,e.points=h[3]?[h[3],h[2],h[1],h[0]]:[h[2],h[1],h[0]],e}).reverse();var m=s[0].points[0],g=s[o-1].points[s[o-1].points.length-1],w=d[o-1].points[d[o-1].points.length-1],y=d[0].points[0],v=f.makeline(w,m),b=f.makeline(g,y),x=[v].concat(s).concat([b]).concat(d),_=x.length;return new c(x)},outlineshapes:function(e,t,n){t=t||e;for(var a=this.outline(e,t).curves,r=[],o=1,s=a.length,d;oi++);if(100<=i)break;y=y?y:w,t.push(y),n=u}while(1>a);return t}},e.exports=y})()},function(e,t,n){var a=n(204),i=function(){this.data={},this.data=a};i.prototype={getSectionLocale:function(e){return this.data[e].locale},getContent:function(e,t){return this.data[e].getContent(t)},getTitle:function(e){return this.data[e].title}},e.exports=i},function(e,t,n){"use strict";var a=n(67);e.exports=function(e){for(var t;(t=e._renderedNodeType)===a.COMPOSITE;)e=e._renderedComponent;if(t===a.HOST)return e._renderedComponent;return t===a.EMPTY?null:void 0}},function(e,t,n){"use strict";function a(e,t){for(var n=d(e.length,t.length),a=0;a.":"function"==typeof t?" Instead of passing a class like Foo, pass React.createElement(Foo) or .":null!=t&&void 0!==t.props?" This may be caused by unintentionally loading two independent copies of React.":""),!1;var o=w.createElement(V,{child:t}),s;if(e){var d=C.get(e);s=d._processChildContext(d._context)}else s=L;var l=p(n);if(l){var u=l._currentElement,h=u.props.child;if(A(h,t)){var g=l._renderedComponent.getPublicInstance(),f=a&&function(){a.call(g)};return q._updateRootComponent(l,o,s,n,f),g}q.unmountComponentAtNode(n)}var y=i(n),v=y&&!!r(y),b=c(n),x=q._renderNewRootComponent(o,n,v&&!l&&!b,s)._renderedComponent.getPublicInstance();return a&&a.call(x),x},render:function(e,t,n){return q._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){!1,u(e)||!1?void 0:m("40"),!1;var t=p(e);if(!t){var n=c(e),a=1===e.nodeType&&e.hasAttribute(O);return!1,!1}return delete j[t._instance.rootID],P.batchedUpdates(l,t,e,!1),!0},_mountImageIntoNode:function(e,t,n,r,o){if(u(t)||!1?void 0:m("41"),r){var s=i(t);if(S.canReuseMarkup(e,s))return void b.precacheNode(n,s);var d=s.getAttribute(S.CHECKSUM_ATTR_NAME);s.removeAttribute(S.CHECKSUM_ATTR_NAME);var l=s.outerHTML;s.setAttribute(S.CHECKSUM_ATTR_NAME,d);var c=e,h=a(c,l),p=" (client) "+c.substring(h-20,h+20)+"\n (server) "+l.substring(h-20,h+20);t.nodeType===R&&1?m("42",p):void 0,!1}if(t.nodeType===R&&1?m("43"):void 0,o.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);g.insertTreeBefore(t,e,null)}else B(t,e),b.precacheNode(n,t.firstChild)}};e.exports=q},function(e){"use strict";e.exports=function(t){if(t=t||("undefined"==typeof document?void 0:document),"undefined"==typeof t)return null;try{return t.activeElement||t.body}catch(n){return t.body}}},function(e,t,n){"use strict";function a(e){return r(document.documentElement,e)}var i=n(236),r=n(234),o=n(73),s=n(59),l={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:l.hasSelectionCapabilities(e)?l.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,i=e.selectionRange;t!==n&&a(n)&&(l.hasSelectionCapabilities(n)&&l.setSelection(n,i),o(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=i.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,a=t.end;if(void 0===a&&(a=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=d(a,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var r=e.createTextRange();r.collapse(!0),r.moveStart("character",n),r.moveEnd("character",a-n),r.select()}else i.setOffsets(e,t)}};e.exports=l},function(e,t,n){"use strict";var a=n(12);e.exports={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):(!1,{remove:a})},registerDefault:function(){}}},function(e,t,n){"use strict";function a(e){var t=Function.prototype.toString,n=Object.prototype.hasOwnProperty,a=RegExp("^"+t.call(n).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");try{var i=t.call(e);return a.test(i)}catch(e){return!1}}function r(e){var t=m(e);if(t){var n=t.childIDs;g(e),n.forEach(r)}}function i(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")}function o(e){return null==e?"#empty":"string"==typeof e||"number"==typeof e?"#text":"string"==typeof e.type?e.type:e.type.displayName||e.type.name||"Unknown"}function s(e){var t=T.getDisplayName(e),n=T.getElement(e),a=T.getOwnerID(e),r;return a&&(r=T.getDisplayName(a)),!1,i(t,n&&n._source,r)}var d=n(25),l=n(13),c=n(24),u=n(31),h="function"==typeof Array.from&&"function"==typeof Map&&a(Map)&&null!=Map.prototype&&"function"==typeof Map.prototype.keys&&a(Map.prototype.keys)&&"function"==typeof Set&&a(Set)&&null!=Set.prototype&&"function"==typeof Set.prototype.keys&&a(Set.prototype.keys),p,m,g,f,w,y,v;if(h){var b=new Map,x=new Set;p=function(e,t){b.set(e,t)},m=function(e){return b.get(e)},g=function(e){b["delete"](e)},f=function(){return Array.from(b.keys())},w=function(e){x.add(e)},y=function(e){x["delete"](e)},v=function(){return Array.from(x.keys())}}else{var _={},E={},C=function(e){return"."+e},k=function(e){return parseInt(e.substr(1),10)};p=function(e,t){var n=C(e);_[n]=t},m=function(e){var t=C(e);return _[t]},g=function(e){var t=C(e);delete _[t]},f=function(){return Object.keys(_).map(k)},w=function(e){var t=C(e);E[t]=!0},y=function(e){var t=C(e);delete E[t]},v=function(){return Object.keys(E).map(k)}}var S=[],T={onSetChildren:function(e,t){var n=m(e);n||!1?void 0:d("144"),n.childIDs=t;for(var a=0;at||e.hasOverloadedBooleanValue&&!1===t}var r=n(17),o=n(4),s=n(8),d=n(264),l=n(3),c=new RegExp("^["+r.ATTRIBUTE_NAME_START_CHAR+"]["+r.ATTRIBUTE_NAME_CHAR+"]*$"),u={},h={},p={createMarkupForID:function(e){return r.ID_ATTRIBUTE_NAME+"="+d(e)},setAttributeForID:function(e,t){e.setAttribute(r.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return r.ROOT_ATTRIBUTE_NAME+"=\"\""},setAttributeForRoot:function(e){e.setAttribute(r.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=r.properties.hasOwnProperty(e)?r.properties[e]:null;if(n){if(i(n,t))return"";var a=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&!0===t?a+"=\"\"":a+"="+d(t)}return r.isCustomAttribute(e)?null==t?"":e+"="+d(t):null},createMarkupForCustomAttribute:function(e,t){return a(e)&&null!=t?e+"="+d(t):""},setValueForProperty:function(e,t,n){var a=r.properties.hasOwnProperty(t)?r.properties[t]:null;if(a){var o=a.mutationMethod;if(o)o(e,n);else{if(i(a,n))return void this.deleteValueForProperty(e,t);if(a.mustUseProperty)e[a.propertyName]=n;else{var s=a.attributeName,d=a.attributeNamespace;d?e.setAttributeNS(d,s,""+n):a.hasBooleanValue||a.hasOverloadedBooleanValue&&!0===n?e.setAttribute(s,""):e.setAttribute(s,""+n)}}}else if(r.isCustomAttribute(t))return void p.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){if(a(t)){null==n?e.removeAttribute(t):e.setAttribute(t,""+n)}},deleteValueForAttribute:function(e,t){e.removeAttribute(t),!1},deleteValueForProperty:function(e,t){var n=r.properties.hasOwnProperty(t)?r.properties[t]:null;if(n){var a=n.mutationMethod;if(a)a(e,void 0);else if(n.mustUseProperty){var i=n.propertyName;e[i]=!n.hasBooleanValue&&""}else e.removeAttribute(n.attributeName)}else r.isCustomAttribute(t)&&e.removeAttribute(t)}};e.exports=p},function(e){"use strict";function t(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var n={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},a=["Webkit","ms","Moz","O"];Object.keys(n).forEach(function(e){a.forEach(function(a){n[t(a,e)]=n[e]})});e.exports={isUnitlessNumber:n,shorthandPropertyExpansions:{background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}}}},function(e){"use strict";e.exports=function(e){try{e.focus()}catch(t){}}},function(e,t,n){"use strict";var a=n(7),i=n(27),r=n(28),o=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t};a.canUseDOM&&!("textContent"in document.documentElement)&&(o=function(e,t){return 3===e.nodeType?void(e.nodeValue=t):void r(e,i(t))}),e.exports=o},function(e){"use strict";var t={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){t.currentScrollLeft=e.x,t.currentScrollTop=e.y}};e.exports=t},function(e){"use strict";var t={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=function(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===n?!!t[e.type]:!("textarea"!==n)}},function(e,t,n){"use strict";function a(e){var t=e.type,n=e.nodeName;return n&&"input"===n.toLowerCase()&&("checkbox"===t||"radio"===t)}function i(e){return e._wrapperState.valueTracker}function r(e,t){e._wrapperState.valueTracker=t}function o(e){e._wrapperState.valueTracker=null}function s(e){var t;return e&&(t=a(e)?""+e.checked:e.value),t}var d=n(4),l={_getTrackerFromNode:function(e){return i(d.getInstanceFromNode(e))},track:function(e){if(!i(e)){var t=d.getNodeFromInstance(e),n=a(t)?"checked":"value",s=Object.getOwnPropertyDescriptor(t.constructor.prototype,n),l=""+t[n];t.hasOwnProperty(n)||"function"!=typeof s.get||"function"!=typeof s.set||(Object.defineProperty(t,n,{enumerable:s.enumerable,configurable:!0,get:function(){return s.get.call(this)},set:function(e){l=""+e,s.set.call(this,e)}}),r(e,{getValue:function(){return l},setValue:function(e){l=""+e},stopTracking:function(){o(e),delete t[n]}}))}},updateValueIfChanged:function(e){if(!e)return!1;var t=i(e);if(!t)return l.track(e),!0;var n=t.getValue(),a=s(d.getNodeFromInstance(e));return a!==n&&(t.setValue(a),!0)},stopTracking:function(e){var t=i(e);t&&t.stopTracking()}};e.exports=l},function(e){"use strict";e.exports={logTopLevelRenders:!1}},function(e,t,n){"use strict";function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=n(2),i=n(14),o=n(1),s=function(){function e(t){a(this,e),this._callbacks=null,this._contexts=null,this._arg=t}return e.prototype.enqueue=function(e,t){this._callbacks=this._callbacks||[],this._callbacks.push(e),this._contexts=this._contexts||[],this._contexts.push(t)},e.prototype.notifyAll=function(){var e=this._callbacks,t=this._contexts,n=this._arg;if(e&&t){e.length!==t.length&&1?r("24"):void 0,this._callbacks=null,this._contexts=null;for(var a=0;an;n++)this.points.push({x:this.width/2+t*g(n/6*e),y:this.height/2+t*s(n/6*e)});this.points=this.points.concat(this.points.slice(0,3)),this.closed=this.degree,this.knots=this.formKnots(this.points),this.weights=this.formWeights(this.points),this.props.controller&&this.props.controller(this,this.knots,this.weights,this.closed),this.draw()},draw:function(){var e=this;this.clear(),this.grid(25);var t=this.points[0];this.points.forEach(function(a){e.stroke(200),e.line(a.x,a.y,t.x,t.y),t=a,e.stroke(0),e.circle(t.x,t.y,4)}),this.drawSplineData()},drawSplineData:function(){if(!(this.points.length<=this.degree)){var e=this.points.map(function(e){return[e.x,e.y]});this.drawCurve(e),this.drawKnots(e)}}}},function(e){"use strict";e.exports={degree:3,activeDistance:9,setup:function(){this.size(400,400);for(var e=2*l,t=0;te.error&&(e.error=.1)}}},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(l,c,u,h){var p=u.x-c.x,g=u.y-c.y,f=h.x-u.x,w=h.y-u.y,y=p*o(n/2)-g*d(n/2),v=p*d(n/2)+g*o(n/2),b=f*o(n/2)-w*d(n/2),x=f*d(n/2)+w*o(n/2),_=(c.x+u.x)/2,E=(c.y+u.y)/2,C=(u.x+h.x)/2,k=(u.y+h.y)/2,S=l.utils.lli8(_,E,_+y,E+v,C,k,C+b,k+x),i=l.utils.dist(S,c),r=t(c.y-S.y,c.x-S.x),T=t(u.y-S.y,u.x-S.x),m=t(h.y-S.y,h.x-S.x),N;return rT||T>m)&&(r+=a),r>m&&(N=m,m=r,r=N)):me.angle?e.angle:0,e:0>e.angle?0:e.angle};e.drawArc(i);var r={x:e.w/2+e.r*a(e.angle/2),y:e.w/2+e.r*n(e.angle/2)},o=t.points[0],s=t.points[3],d=this.guessCurve(o,r,s),l=new e.Bezier([o,d[0],d[1],s]);e.setColor("rgb(140,140,255)"),e.drawLine(l.points[0],l.points[1]),e.drawLine(l.points[1],l.points[2]),e.drawLine(l.points[2],l.points[3]),e.setColor("blue"),e.drawCurve(l),e.drawCircle(l.points[1],3),e.drawCircle(l.points[2],3),e.drawSkeleton(t),e.setColor("black"),e.drawLine(t.points[1],t.points[2]),e.drawCurve(t)},onMouseMove:function(e,i){var o=e.offsetX-i.w/2,s=e.offsetY-i.h/2;if(!(o>i.w/2)){var d=h(s,o);0>d&&(d=2*l+d);var c=i.curve.points,u=i.r,r=4*t(d/4)/3;c[1]={x:i.w/2+u,y:i.w/2+u*r},c[2]={x:i.w/2+i.r*(a(d)+r*n(d)),y:i.w/2+i.r*(n(d)-r*a(d))},c[3]={x:i.w/2+i.r*a(d),y:i.w/2+i.r*n(d)},i.setCurve(new i.Bezier(c)),i.angle=d}},drawCircle:function(e){e.setSize(325,325),e.reset();var t=e.getPanelWidth(),n=e.getPanelHeight(),a=t/2-60,i=.55228,r={x:-30,y:-15},o=new e.Bezier([{x:t/2+a,y:n/2},{x:t/2+a,y:n/2+i*a},{x:t/2+i*a,y:n/2+a},{x:t/2,y:n/2+a}]);e.setColor("lightgrey"),e.drawLine({x:0,y:n/2},{x:t+60,y:n/2},r),e.drawLine({x:t/2,y:0},{x:t/2,y:n+60},r);var s=o.points;e.setColor("red"),e.drawPoint(s[0],r),e.drawPoint(s[1],r),e.drawPoint(s[2],r),e.drawPoint(s[3],r),e.drawCurve(o,r),e.setColor("rgb(255,160,160)"),e.drawLine(s[0],s[1],r),e.drawLine(s[1],s[2],r),e.drawLine(s[2],s[3],r),e.setFill("red"),e.text(s[0].x-t/2+","+(s[0].y-n/2),{x:s[0].x+7,y:s[0].y+3},r),e.text(s[1].x-t/2+","+(s[1].y-n/2),{x:s[1].x+7,y:s[1].y+3},r),e.text(s[2].x-t/2+","+(s[2].y-n/2),{x:s[2].x+7,y:s[2].y+7},r),e.text(s[3].x-t/2+","+(s[3].y-n/2),{x:s[3].x,y:s[3].y+13},r),s.forEach(function(e){e.x=-(e.x-t)}),e.setColor("blue"),e.drawCurve(o,r),e.drawLine(s[2],s[3],r),e.drawPoint(s[2],r),e.setFill("blue"),e.text("reflected",{x:s[2].x-30,y:s[2].y+13},r),e.setColor("rgb(200,200,255)"),e.drawLine(s[1],s[0],r),e.drawPoint(s[1],r),s.forEach(function(e){e.y=-(e.y-n)}),e.setColor("green"),e.drawCurve(o,r),s.forEach(function(e){e.x=-(e.x-t)}),e.setColor("purple"),e.drawCurve(o,r),e.drawLine(s[1],s[0],r),e.drawPoint(s[1],r),e.setFill("purple"),e.text("reflected",{x:s[1].x+10,y:s[1].y+3},r),e.setColor("rgb(200,200,255)"),e.drawLine(s[2],s[3],r),e.drawPoint(s[2],r),e.setColor("black"),e.setFill("black"),e.drawLine({x:t/2,y:n/2},{x:t/2+a-2,y:n/2},r),e.drawLine({x:t/2,y:n/2},{x:t/2,y:n/2+a-2},r),e.text("r = "+a,{x:t/2+a/3,y:n/2+10},r)}}},function(e,t,n){"use strict";var a=n(102),i=n(0);e.exports=i("circles_cubic",a)},function(e){"use strict";var t=s,n=g;e.exports={setup:function(e){e.w=e.getPanelWidth(),e.h=e.getPanelHeight(),e.pad=20,e.r=e.w/2-e.pad,e.mousePt=!1,e.angle=0;var t={x:e.w-e.pad,y:e.h/2};e.setCurve(new e.Bezier(t,t,t))},draw:function(e,t){e.reset(),e.setColor("lightgrey"),e.drawGrid(1,1),e.setColor("red"),e.drawCircle({x:e.w/2,y:e.h/2},e.r),e.setColor("transparent"),e.setFill("rgba(100,255,100,0.4)");var n={x:e.w/2,y:e.h/2,r:e.r,s:0>e.angle?e.angle:0,e:0>e.angle?0:e.angle};e.drawArc(n),e.setColor("black"),e.drawSkeleton(t),e.drawCurve(t)},onMouseMove:function(e,a){var i=e.offsetX-a.w/2,o=e.offsetY-a.h/2,s=h(o,i),d=a.curve.points,l=a.r,r=(n(s)-1)/t(s);d[1]={x:a.w/2+l*(n(s)-r*t(s)),y:a.w/2+l*(t(s)+r*n(s))},d[2]={x:a.w/2+a.r*n(s),y:a.w/2+a.r*t(s)},a.setCurve(new a.Bezier(d)),a.angle=s}}},function(e,t,n){"use strict";var a=n(104),i=n(0);e.exports=i("circles",a)},function(e){"use strict";e.exports={statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},setup:function(e,t){e.setCurve(t),e.distance=20},setupQuadratic:function(e){var t=e.getDefaultQuadratic();this.setup(e,t)},setupCubic:function(e){var t=e.getDefaultCubic();this.setup(e,t)},draw:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t),e.setColor("blue");var n=t.outline(0,0,e.distance,e.distance);n.curves.forEach(function(t){return e.drawCurve(t)})}}},function(e,t,n){"use strict";var a=n(106),i=n(0),r=n(10);e.exports=r(i("graduatedoffset",a))},function(e){"use strict";e.exports={statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},setup:function(e,t){e.setCurve(t),e.distance=20},setupQuadratic:function(e){var t=e.getDefaultQuadratic();this.setup(e,t)},setupCubic:function(e){var t=e.getDefaultCubic();this.setup(e,t)},draw:function(e,t){e.reset(),e.drawSkeleton(t);var n=t.reduce();n.forEach(function(t){e.setRandomColor(),e.drawCurve(t),e.drawCircle(t.points[0],1)});var a=n.slice(-1)[0];e.drawPoint(a.points[3]||a.points[2]),e.setColor("red");var i=t.offset(e.distance);i.forEach(function(t){e.drawPoint(t.points[0]),e.drawCurve(t)}),a=i.slice(-1)[0],e.drawPoint(a.points[3]||a.points[2]),e.setColor("blue"),i=t.offset(-e.distance),i.forEach(function(t){e.drawPoint(t.points[0]),e.drawCurve(t)}),a=i.slice(-1)[0],e.drawPoint(a.points[3]||a.points[2])}}},function(e,t,n){"use strict";var a=n(108),i=n(0),r=n(10);e.exports=r(i("offsetting",a))},function(e){"use strict";e.exports={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 a=e.length,r=n(e[0],t),o=0,s,l;for(s=1;sn;n++)a=t+(2*n-2)+e.lpts.length,a=e.lpts[a%e.lpts.length],i=t+(2*n-1),i=e.lpts[i%e.lpts.length],r=t+2*n,r=e.lpts[r%e.lpts.length],r.x=i.x+(i.x-a.x),r.y=i.y+(i.y-a.y);r=t+6,r=e.lpts[r%e.lpts.length],e.problem=r},movePointsCubicLD:function(e,t){var n,a;1==t%3?(a=t-1,a+=0>a?e.lpts.length:0,n=t-2,n+=0>n?e.lpts.length:0):(a=(t+1)%e.lpts.length,n=(t+2)%e.lpts.length),a=e.lpts[a],n=e.lpts[n],n.x=a.x+(a.x-e.mp.x),n.y=a.y+(a.y-e.mp.y)},linkDerivatives:function(e,t){if(t.mp){var n=8===t.lpts.length,a=t.mp_idx;n?0!=a%2&&this.movePointsQuadraticLD(t,a):0!=a%3&&this.movePointsCubicLD(t,a)}},movePointsQuadraticDirOnly:function(e,s){var i,l,c;[-1,1].forEach(function(u){i=e.mp,l=s+u+e.lpts.length,l=e.lpts[l%e.lpts.length],c=s+2*u+e.lpts.length,c=e.lpts[c%e.lpts.length];var h=t(l.y-i.y,l.x-i.x),a=c.x-l.x,p=c.y-l.y,m=n(a*a+p*p);c.x=l.x+m*o(h),c.y=l.y+m*r(h)}),c=s+4,c=e.lpts[c%e.lpts.length],e.problem=c},movePointsCubicDirOnly:function(e,s){var i,l;1==s%3?(l=s-1,l+=0>l?e.lpts.length:0,i=s-2,i+=0>i?e.lpts.length:0):(l=(s+1)%e.lpts.length,i=(s+2)%e.lpts.length),l=e.lpts[l],i=e.lpts[i];var c=t(l.y-e.mp.y,l.x-e.mp.x),a=i.x-l.x,u=i.y-l.y,h=n(a*a+u*u);i.x=l.x+h*o(c),i.y=l.y+h*r(c)},linkDirection:function(e,t){if(t.mp){var n=8===t.lpts.length,a=t.mp_idx;n?0!=a%2&&this.movePointsQuadraticDirOnly(t,a):0!=a%3&&this.movePointsCubicDirOnly(t,a)}},bufferPoints:function(e,t){t.bpts=JSON.parse(JSON.stringify(t.lpts))},moveQuadraticPoint:function(e,s){this.moveCubicPoint(e,s),[-1,1].forEach(function(i){var l=s-i+e.lpts.length;l=e.lpts[l%e.lpts.length];var c=s-2*i+e.lpts.length;c=e.lpts[c%e.lpts.length];var u=s-3*i+e.lpts.length;u=e.lpts[u%e.lpts.length];var h=t(c.y-l.y,c.x-l.x),a=u.x-c.x,p=u.y-c.y,m=n(a*a+p*p);u.x=c.x+m*o(h),u.y=c.y+m*r(h)});var a=s+4;a=e.lpts[a%e.lpts.length],e.problem=a},moveCubicPoint:function(e,t){var n=e.bpts[t],a=e.lpts[t],i=a.x-n.x,o=a.y-n.y,s=e.lpts.length,d=t-1+s,l=t+1,r=e.bpts[d%s],c=e.bpts[l%s],u=e.lpts[d%s],h=e.lpts[l%s];return u.x=r.x+i,u.y=r.y+o,h.x=c.x+i,h.y=c.y+o,{x:i,y:o}},modelCurve:function(e,t){if(t.mp){var n=8===t.lpts.length,a=t.mp_idx;n?0==a%2?this.moveQuadraticPoint(t,a):this.movePointsQuadraticDirOnly(t,a):0==a%3?this.moveCubicPoint(t,a):this.movePointsCubicDirOnly(t,a)}},draw:function(e){e.reset();var t=e.lpts,n=8===t.length,a=n?new e.Bezier(t[0],t[1],t[2]):new e.Bezier(t[0],t[1],t[2],t[3]);e.drawSkeleton(a,!1,!0),e.drawCurve(a);var i=n?new e.Bezier(t[2],t[3],t[4]):new e.Bezier(t[3],t[4],t[5],t[6]);e.drawSkeleton(i,!1,!0),e.drawCurve(i);var r=n?new e.Bezier(t[4],t[5],t[6]):new e.Bezier(t[6],t[7],t[8],t[9]);e.drawSkeleton(r,!1,!0),e.drawCurve(r);var o=n?new e.Bezier(t[6],t[7],t[0]):new e.Bezier(t[9],t[10],t[11],t[0]);e.drawSkeleton(o,!1,!0),e.drawCurve(o),e.problem&&(e.setColor("red"),e.drawCircle(e.problem,5))}}},function(e,t,n){"use strict";var a=n(114),i=n(0);e.exports=i("polybezier",a)},function(e){"use strict";e.exports={statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},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,a){return[t,{x:t.x+(n.x-e.x)/3,y:t.y+(n.y-e.y)/3},{x:n.x-(a.x-t.x)/3,y:n.y-(a.y-t.y)/3},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(),a=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:a},i),t.forEach(function(t){e.drawCircle(t,3,i)});var r=t[0],o=t[1],s=t[2],d=s.x-r.x,l=s.y-r.y,c=u(d*d+l*l);d/=c,l/=c,e.drawLine(r,s,i);var h={x:r.x+(s.x-o.x)-e.distance*d,y:r.y+(s.y-o.y)-e.distance*l},p={x:r.x+(s.x-o.x)+e.distance*d,y:r.y+(s.y-o.y)+e.distance*l},m=e.utils.lli4(r,s,o,{x:(h.x+p.x)/2,y:(h.y+p.y)/2});e.setColor("blue"),e.drawCircle(m,3,i),e.drawLine(t[1],m,i),e.setColor("#666"),e.drawLine(m,h,i),e.drawLine(m,p,i),e.setFill("blue"),e.text("p0",h,{x:-20+i.x,y:i.y+2}),e.text("p4",p,{x:10+i.x,y:i.y+2}),e.setColor("red"),e.drawCircle(h,3,i),e.drawLine(o,h,i),e.drawLine(r,{x:r.x+(o.x-h.x)/5,y:r.y+(o.y-h.y)/5},i),e.setColor("#00FF00"),e.drawCircle(p,3,i),e.drawLine(o,p,i),e.drawLine(s,{x:s.x+(p.x-o.x)/5,y:s.y+(p.y-o.y)/5},i);var g=new e.Bezier(this.convert(h,r,o,s)),f=new e.Bezier(this.convert(r,o,s,p));e.setColor("lightgrey"),e.drawCurve(g,i),e.drawCurve(f,i),i.x+=n,e.setColor("lightblue"),e.drawGrid(10,10,i),e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:a},i),e.drawCurve(g,i),e.drawCurve(f,i),e.drawPoints(g.points,i),e.drawPoints(f.points,i),e.setColor("lightgrey"),e.drawLine(g.points[0],g.points[1],i),e.drawLine(g.points[2],f.points[1],i),e.drawLine(f.points[2],f.points[3],i)}}},function(e,t,n){"use strict";var a=n(116),i=n(0),r=n(10);e.exports=r(i("catmullmoulding",a))},function(e,t,n){"use strict";var a=n(0);e.exports=a("catmullconv")},function(e,t,n){function a(e,t){if(0===e)return 1;for(var n=y;e>=n.length;){for(var a=n.length,r=[1],o=1,s=a-1;ot.push([])),e.forEach((e,n)=>e.forEach((e,a)=>t[a][n]=e)),t}function i(e,t){return e[t]}function d(e,t){for(var n=[],a=0,i=e.length;ae+u[n]*t;n[o][s]=l.reduce(h,0)}}return n}function c(e,t){var n=[];return e.forEach(e=>n.push([e[t]])),n}function h(e){for(var t=[],n=e;n--;)t[n]="0".repeat(e).split("").map(e=>parseInt(e));for(n=0;nr(e,t))}function m(e,t){t=t||e.length;for(var a=[],r=0;r{s[t]=e/d}),s},v.equidistant=function(e,t){return"0".repeat(t).split("").map((e,n)=>n/(t-1))},f.modes=["polygonal","equidistant"],e.exports=window.makeFit=f},function(e,t,n){"use strict";var a=n(119);e.exports={setup:function(e){this.api=e,e.noDrag=!0,this.reset()},reset:function(){if(this.points=[],this.sliders.setOptions([]),this.curveset=!1,this.mode=0,this.api){var e=this.api;e.setCurve(!1),e.reset(),e.redraw()}},toggle:function(){this.api&&(this.customTimeValues=!1,this.mode=(this.mode+1)%a.modes.length,this.fitCurve(this.api),this.api.redraw())},draw:function(e,t){e.setPanelCount(1),e.reset(),e.setColor("lightgrey"),e.drawGrid(10,10),e.setColor("black"),!this.curveset&&2a||.95t.t||.95t.c1.length()&&.6>t.c2.length())return a.finals.push(t);var n=t.c1.split(.5);e.setColor("black"),e.drawCurve(t.c1,r),e.setColor("red"),e.drawbbox(n.left.bbox(),r),e.drawbbox(n.right.bbox(),r);var i=t.c2.split(.5);e.setColor("black"),e.drawCurve(t.c2,r),e.setColor("blue"),e.drawbbox(i.left.bbox(),r),e.drawbbox(i.right.bbox(),r),n.left.overlaps(i.left)&&a.pairs.push({c1:n.left,c2:i.left}),n.left.overlaps(i.right)&&a.pairs.push({c1:n.left,c2:i.right}),n.right.overlaps(i.left)&&a.pairs.push({c1:n.right,c2:i.left}),n.right.overlaps(i.right)&&a.pairs.push({c1:n.right,c2:i.right})}),this.prevstep=this.step}else this.pairs.forEach(function(t){e.setColor("black"),e.drawCurve(t.c1,r),e.drawCurve(t.c2,r),e.setColor("red"),e.drawbbox(t.c1.bbox(),r),e.setColor("blue"),e.drawbbox(t.c2.bbox(),r)});0===this.pairs.length&&(this.pairReset(),this.draw(e,n)),r.x+=o,e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:s},r);var l=n[0].intersects(n[1]).map(function(e){var t=e.split("/").map(function(e){return parseFloat(e)});return{t1:t[0],t2:t[1]}}),c=l[0],u=function(e,n){return .01>t(e.t1-n.t1)&&.01>t(e.t2-n.t2)},h,p;for(p=1;p=r.x&&c>=r.y&&(e.setColor("#00FF00"),o++)}e.drawCurve(a)}),r&&(e.setColor(2>o?"red":"#00FF00"),e.drawCircle(r,3))},setupQuadratic:function(e){var t=e.getDefaultQuadratic(),n=new e.Bezier([15,250,220,20]);e.setCurve(t,n)},setupCubic:function(e){var t=new e.Bezier([100,240,30,60,210,230,160,30]),n=new e.Bezier([25,260,230,20]);e.setCurve(t,n)},draw:function(e,n){e.reset(),n.forEach(function(t){e.drawSkeleton(t),e.drawCurve(t)});var t=e.utils,a={p1:n[1].points[0],p2:n[1].points[1]},i=t.align(n[0].points,a),r=new e.Bezier(i),o=t.roots(r.points);o.forEach(function(a){var t=n[0].get(a);e.drawCircle(t,3),e.text("t = "+a,{x:t.x+5,y:t.y+10})})}}},function(e,t,n){"use strict";var a=n(130),i=n(0);e.exports=i("intersections",a)},function(e){"use strict";e.exports={statics:{keyHandlingOptions:{propName:"steps",values:{38:1,40:-1},controller:function(e){1>e.steps&&(e.steps=1)}}},setup:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.steps=8},generate:function(e,n,a,i,r){a.x+=i,a.y+=i;for(var o=n.length(),s=[{x:0,y:0,d:0}],l=1,c,u;100>=l;l++)c=l/100,u=n.split(c).left.length(),s.push({x:e.utils.map(c,0,1,0,r),y:e.utils.map(u,0,o,0,r),d:u,t:c});return s},draw:function(e,t,n){e.reset(),e.drawSkeleton(t),e.drawCurve(t);var a=t.length(),i=e.getPanelWidth(),r=e.getPanelHeight(),o=20;return n.x+=i,e.drawLine({x:0,y:0},{x:0,y:r},n),e.drawAxes(o,"t",0,1,"d",0,a,n),this.generate(e,t,n,o,i-2*o)},plotOnly:function(e,t){e.setPanelCount(2);for(var n={x:0,y:0},a=this.draw(e,t,n),r=0;rm){h--;break}0>h&&(h=0),h===l.length&&(h=l.length-1),s.push(l[h])}for(u=0;ur;r++)e.setColor("rgba(255,127,"+r+",0.6)"),o=r/255,d=a.get(o),l=a.normal(o),u=a.curvature(o),h=u.k*l.x,m=u.k*l.y,e.drawLine(d,{x:d.x+h,y:d.y+m}),i&&(e.setColor("rgba("+r+",127,255,0.6)"),e.drawLine(d,{x:d.x-h,y:d.y-m}))},proxyDraw:function(e,t,n){var a=this;e.reset(),this.updateCurves(e,t),[this.q,this.c].forEach(function(t){return a.drawCurvature(e,t,n)})},draw:function(e,t){this.proxyDraw(e,t)},drawOmni:function(e,t){this.proxyDraw(e,t,!0)}}},function(e,t,n){"use strict";var a=n(134),i=n(0);e.exports=i("curvature",a)},function(e){"use strict";e.exports={statics:{keyHandlingOptions:{propName:"steps",values:{38:1,40:-1},controller:function(e){1>e.steps&&(e.steps=1)}}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t),e.steps=10},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.steps=16},draw:function(e,n){e.reset(),e.drawSkeleton(n);for(var a=n.getLUT(e.steps),r=1/e.steps,o=n.points[0],s=r,l;s<1+r;s+=r)l=n.get(d(s,1)),e.setColor("red"),e.drawLine(o,l),o=l;for(var c=n.length(),h=0,p=0,m,g,f;p=n?1:0;e.reset(),e.setColor("transparent"),e.setFill("rgba(150,150,255, 0.4)");for(var l=t/n,c=l/2,u,h,p;c=e});var d=s[0],t=n.get(d);e.drawLine({x:t.x,y:t.y},{x:t.x,y:i}),e.drawLine({x:t.x,y:t.y},{x:0,y:t.y}),e.text("y="+(0|t.y),{x:t.x/2,y:t.y-5}),e.text("x="+(0|t.x),{x:o+5,y:i-(i-t.y)/2}),e.text("t="+(0|100*d)/100,{x:o+15,y:t.y})}}}};e.exports=t},function(e,t,n){"use strict";var a=n(140),i=n(0);e.exports=i("yforx",a)},function(e){"use strict";e.exports={setup:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.reset(),e._map_loaded=!1},draw:function(e,t){var n=this.unit,a={x:200,y:200};e.setSize(400,400),e.setPanelCount(2),e.reset(),e.drawSkeleton(t),e.drawCurve(t),e.offset.x+=400,e._map_loaded?e.image(e._map_image):setTimeout(function(){this.drawBase(e,t),this.draw(e,t)}.bind(this),100),e.drawLine({x:0,y:0},{x:0,y:400});var i=[{x:0,y:0},{x:0,y:n},{x:n,y:n},this.forwardTransform(t.points,n)],r=new e.Bezier(i);e.setColor("blue"),e.drawCurve(r,a),e.drawCircle(i[3],3,a)},forwardTransform:function(e,t){t=t||1;var n=e[0],a=e[1],i=e[2],r=e[3],o=-n.x+r.x-(-n.x+a.x)*(-n.y+r.y)/(-n.y+a.y),d=-n.x+i.x-(-n.x+a.x)*(-n.y+i.y)/(-n.y+a.y),l=t*o/d,c=t*(-n.y+r.y)/(-n.y+a.y),u=t-t*(-n.y+i.y)/(-n.y+a.y);return{x:l,y:c+u*o/d}},drawBase:function(e){e.reset();var t=this.unit=80,n={x:200,y:200};e.setSize(400,400),e.setColor("lightgrey");for(var a=0;a<400;a+=t/2)e.drawLine({x:a,y:0},{x:a,y:400});for(var i=0;i<400;i+=t/2)e.drawLine({x:0,y:i},{x:400,y:i});e.setColor("black"),e.drawLine({x:200,y:0},{x:200,y:400}),e.drawLine({x:0,y:200},{x:400,y:200}),e.setColor("green"),e.drawLine({x:-200,y:t},{x:200,y:t},n),e.setColor("black"),e.setFill("black"),e.drawCircle({x:0,y:0},4,n),e.text("(0,0)",{x:5+n.x,y:15+n.y}),e.drawCircle({x:0,y:t},4,n),e.text("(0,1)",{x:5+n.x,y:t+15+n.y}),e.drawCircle({x:t,y:t},4,n),e.text("(1,1)",{x:t+5+n.x,y:t+15+n.y}),e.setWeight(1.5),e.setColor("#FF0000"),e.setFill(e.getColor());var r=[],o=1,s=1;for(a=-10;1>=a;a+=.01)i=(-a*a+2*a+3)/4,-10-400;a-=.01)r.push({x:t*o,y:t*s}),i=(-a*a+3*a)/3,e.drawLine({x:t*o,y:t*s},{x:t*a,y:t*i},n),o=a,s=i;r.push({x:t*o,y:t*s}),e.text("\u2190 Curve forms a loop at t = 0",{x:200-t+10,y:200-1.25*t}),e.setColor("transparent"),e.setFill("rgba(255,120,100,0.2)"),e.drawPath(r,n),r=[{x:-200,y:t},{x:200,y:t},{x:200,y:400},{x:-200,y:400}],e.setFill("rgba(0,200,0,0.2)"),e.drawPath(r,n),e.setColor("black"),e.setFill(e.getColor()),e.text("\u2190 Curve form has one inflection \u2192",{x:200-t,y:200+1.75*t}),e.text("\u2190 Plain curve \u2195",{x:200+t/2,y:400/6}),e.text("\u2195 Double inflection",{x:10,y:190}),e._map_image=e.toImage(),e._map_loaded=!0}}},function(e,t,n){"use strict";var a=n(142),i=n(0);e.exports=i("canonical",a)},function(e){"use strict";e.exports={setupCubic:function(e){var t=new e.Bezier(135,25,25,135,215,75,215,240);e.setCurve(t)},draw:function(e,n){e.reset(),e.drawSkeleton(n),e.drawCurve(n),e.setColor("red"),n.inflections().forEach(function(a){e.drawCircle(n.get(a),5)})}}},function(e,t,n){"use strict";var a=n(144),i=n(0);e.exports=i("inflections",a)},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},align:function(e,t){var n=t.p1.x,i=t.p1.y,r=-h(t.p2.y-i,t.p2.x-n),a=g,o=s;return e.map(function(e){return{x:(e.x-n)*a(r)-(e.y-i)*o(r),y:(e.x-n)*o(r)+(e.y-i)*a(r),a:r}})},transpose:function(e,t,n){var a=n.x,i=n.y,r=g,o=s,d=[e.x.min,e.y.min,e.x.max,e.y.max];return[{x:d[0],y:d[1]},{x:d[2],y:d[1]},{x:d[2],y:d[3]},{x:d[0],y:d[3]}].map(function(e){var n=e.x,s=e.y;return{x:n*r(t)-s*o(t)+a,y:n*o(t)+s*r(t)+i}})},draw:function(e,t){e.reset();var n=t.points,a={p1:n[0],p2:n[n.length-1]},i=this.align(n,a),r=-i[0].a,o=new e.Bezier(i),s=o.bbox(),d=this.transpose(s,r,n[0]);e.setColor("#00FF00"),e.drawLine(d[0],d[1]),e.drawLine(d[1],d[2]),e.drawLine(d[2],d[3]),e.drawLine(d[3],d[0]),e.setColor("black"),e.drawSkeleton(t),e.drawCurve(t)}}},function(e,t,n){"use strict";var a=n(146),i=n(0);e.exports=i("tightbounds",a)},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},align:function(e,t){var n=t.p1.x,i=t.p1.y,r=-h(t.p2.y-i,t.p2.x-n),a=g,o=s;return e.map(function(e){return{x:(e.x-n)*a(r)-(e.y-i)*o(r),y:(e.x-n)*o(r)+(e.y-i)*a(r)}})},draw:function(e,t){e.setPanelCount(2),e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=t.points,a={p1:n[0],p2:n[n.length-1]},i=this.align(n,a),r=new e.Bezier(i),o=e.getPanelWidth(),s=e.getPanelHeight(),d={x:o,y:0};e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:s},d),d.x+=o/4,d.y+=s/2,e.setColor("grey"),e.drawLine({x:0,y:-s/2},{x:0,y:s/2},d),e.drawLine({x:-o/4,y:0},{x:o,y:0},d),e.setFill("grey"),e.setColor("black"),e.drawSkeleton(r,d),e.drawCurve(r,d)}}},function(e,t,n){"use strict";var a=n(148),i=n(0);e.exports=i("aligning",a)},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,n){e.reset(),e.setColor("#00FF00"),e.drawbbox(n.bbox()),e.setColor("black"),e.drawSkeleton(n),e.drawCurve(n),e.setColor("red"),n.extrema().values.forEach(function(a){e.drawCircle(n.get(a),3)})}}},function(e,t,n){"use strict";var a=n(150),i=n(0);e.exports=i("boundingbox",a)},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=e.getDefaultQuadratic();t.points[2].x=210,e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.setPanelCount(3),e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=t.order+1,a=t.points,i=e.getPanelWidth(),r=e.getPanelHeight(),o={x:i,y:0},s=JSON.parse(JSON.stringify(a)).map(function(e,a){return{x:i*a/n,y:e.x}});e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},o),e.drawAxes(20,"t",0,1,"x",0,i,o),o.x+=20;var d=new e.Bezier(s);e.drawCurve(d,o),e.setColor("red"),d.extrema().y.forEach(function(n){var t=d.get(n);e.drawCircle(t,3,o)}),o.x+=i-20;var l=JSON.parse(JSON.stringify(a)).map(function(e,a){return{x:i*a/n,y:e.y}});e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},o),e.drawAxes(20,"t",0,1,"y",0,i,o),o.x+=20;var c=new e.Bezier(l);e.drawCurve(c,o),e.setColor("red"),c.extrema().y.forEach(function(n){var t=c.get(n);e.drawCircle(t,3,o)})}}},function(e,t,n){"use strict";var a=n(152),i=n(0);e.exports=i("extremities",a)},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=e.getDefaultQuadratic();t.points[2].x=210,e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.setPanelCount(3),e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=t.order,a=t.points,i=e.getPanelWidth(),r=i-40,o=e.getPanelHeight(),s={x:i,y:0},d=JSON.parse(JSON.stringify(a)).map(function(e,a){return{x:r*a/n,y:e.x}});e.drawLine({x:0,y:0},{x:0,y:o},s),e.drawAxes(20,"t",0,1,"x",0,i-20,s),s.x+=20,s.y+=20,e.drawCurve(new e.Bezier(d),s),s.x+=i-20,s.y-=20;var l=JSON.parse(JSON.stringify(a)).map(function(e,a){return{x:r*a/n,y:e.y}});e.drawLine({x:0,y:0},{x:0,y:o},s),e.drawAxes(20,"t",0,1,"y",0,i-20,s),s.x+=20,s.y+=20,e.drawCurve(new e.Bezier(l),s)}}},function(e,t,n){"use strict";var a=n(154),i=n(0);e.exports=i("components",a)},function(e){"use strict";function a(e){var t=u(e.x*e.x+e.y*e.y+e.z*e.z);return{x:e.x/t,y:e.y/t,z:e.z/t}}function t(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function n(e,t){return{x:t*e.x,y:t*e.y,z:t*e.z}}function i(e,t){return{x:e.x+t.x,y:e.y+t.y,z:e.z+t.z}}function r(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}function s(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}function o(e,t,n){return{x:(1-e)*t.x+e*n.x,y:(1-e)*t.y+e*n.y,z:(1-e)*t.z+e*n.z}}var d=!0,l;e.exports={setup:function(e){l={x:2*e.getPanelWidth()/5,y:4*e.getPanelHeight()/5},e.setSize(1.25*e.getPanelWidth(),e.getPanelHeight())},drawCube:function(e){var t=function(t){return e.project(t,l)},n=[{x:0,y:0,z:0},{x:200,y:0,z:0},{x:200,y:200,z:0},{x:0,y:200,z:0},{x:0,y:0,z:200},{x:200,y:0,z:200},{x:200,y:200,z:200},{x:0,y:200,z:200}].map(function(e){return t(e)});e.setColor("grey"),e.drawLine(n[1],n[2]),e.drawLine(n[2],n[3]),e.drawLine(n[1],n[5]),e.drawLine(n[2],n[6]),e.drawLine(n[3],n[7]),e.drawLine(n[4],n[5]),e.drawLine(n[5],n[6]),e.drawLine(n[6],n[7]),e.drawLine(n[7],n[4]),e.setColor("blue"),e.drawLine(n[0],n[1]),e.setColor("red"),e.drawLine(n[3],n[0]),e.setColor("green"),e.drawLine(n[0],n[4])},drawCurve:function(e,t,n){var a=function(t){return e.project(t,l)},i=t.map(function(e){return a(e)});n&&(e.setColor("rgba(0,0,0,"+.2+")"),e.drawCurve({points:t.map(function(t){return e.projectXY(t,l)})}),e.drawCurve({points:t.map(function(t){return e.projectYZ(t,l)})}),e.drawCurve({points:t.map(function(t){return e.projectXZ(t,l)})})),e.setColor("#333"),e.drawLine(i[0],i[1]),e.drawCircle(i[1],3),e.drawCircle(i[2],3),e.drawLine(i[2],i[3]),e.setColor("black"),e.drawCircle(i[0],3),e.drawCircle(i[3],3);new e.Bezier(i);e.drawCurve({points:i})},getFrenetVectors:function(e,t,d){var l=t.get(e),o=d.get(e),c=d.derivative(e),u=a(i(o,c)),h=a(s(u,o)),r=a(s(h,o));return{o:l,dt:o,r:h,n:r}},lerpVectors:function(e,t,n){var a={};return["o","dt","r","n"].forEach(function(i){a[i]=o(e,t[i],n[i])}),a},generateRMF:function(e,a){var i=[],o=.05;i.push(this.getFrenetVectors(0,e,a));for(var d=0;1>=d;d+=o){var l=i.slice(-1)[0],c=d+o,u={o:e.get(c),dt:a.get(c)},h=r(u.o,l.o),p=t(h,h),m=r(l.r,n(h,2/p*t(h,l.r))),g=r(l.dt,n(h,2/p*t(h,l.dt))),f=r(u.dt,g),w=t(f,f);u.r=r(m,n(f,2/w*t(f,m))),u.n=s(u.r,u.dt),i.push(u)}return i},getRMF:function(e,n,a){this.rmf_LUT||(this.rmf_LUT=this.generateRMF(n,a));var r=this.rmf_LUT.length,o=e*r;if(o!=(0|o)){if(o|=0,o===r-1)return this.rmf_LUT[o-1];var s=o+1,d=o/r;return e=(e-d)/(s/r-d),this.lerpVectors(e,this.rmf_LUT[o],this.rmf_LUT[s])}return this.rmf_LUT[o]},drawVector:function(e,t,n,i,o,r,s){var d=function(t){return e.project(t,l)};n=a(n),n={x:t.x+i*n.x,y:t.y+i*n.y,z:t.z+i*n.z},e.setColor("rgba("+o+","+r+","+s+",1)"),e.drawLine(d(t),d(n))},drawFrenetVectors:function(e){e.reset();var n=function(t){return e.project(t,l)};this.drawCube(e);var a=[{x:120,y:0,z:0},{x:120,y:220,z:0},{x:30,y:0,z:30},{x:0,y:0,z:200}];this.drawCurve(e,a,d);var i=new e.Bezier(a),r=new e.Bezier(i.dpoints[0]),o=w(e.hover.x?e.hover.x/e.getPanelWidth():0,0),t=i.get(o);e.drawCircle(n(t),3);var s=this.getFrenetVectors(o,i,r);this.drawVector(e,t,s.dt,40,0,200,0),this.drawVector(e,t,s.r,40,0,0,200),this.drawVector(e,t,s.n,40,200,0,0)},drawRMFNormals:function(e){e.reset();var n=function(t){return e.project(t,l)};this.drawCube(e);var a=[{x:120,y:0,z:0},{x:120,y:220,z:0},{x:30,y:0,z:30},{x:0,y:0,z:200}];this.drawCurve(e,a,d);var i=new e.Bezier(a),r=new e.Bezier(i.dpoints[0]),o=w(e.hover.x?e.hover.x/e.getPanelWidth():0,0),t=i.get(o);e.drawCircle(n(t),3);var s=this.getRMF(o,i,r);this.drawVector(e,t,s.dt,40,0,200,0),this.drawVector(e,t,s.r,40,0,0,200),this.drawVector(e,t,s.n,40,200,0,0)}}},function(e,t,n){"use strict";var a=n(156),i=n(0);e.exports=i("pointvectors3d",a)},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,a){e.reset(),e.drawSkeleton(a);var r,o,s,d,l,c;for(r=0;10>=r;r++)o=r/10,s=a.get(o),d=a.derivative(o),c=u(d.x*d.x+d.y*d.y),d={x:d.x/c,y:d.y/c},l=a.normal(o),e.setColor("blue"),e.drawLine(s,{x:s.x+20*d.x,y:s.y+20*d.y}),e.setColor("red"),e.drawLine(s,{x:s.x+20*l.x,y:s.y+20*l.y}),e.setColor("black"),e.drawCircle(s,3)}}},function(e,t,n){"use strict";var a=n(158),i=n(0);e.exports=i("pointvectors",a)},function(e,t,n){"use strict";var a=n(0);e.exports=a("derivatives")},function(e,t,n){var a=n(50);e.exports=function(e,t){var n=[],i=a(t);return e.forEach((e,t)=>{n[t]=[],i.forEach((a,i)=>{n[t][i]=e.map((e,t)=>a[t]*e).reduce((e,t)=>e+t,0)})}),n}},function(e,t,n){"use strict";var a=n(51),r=n(161),o=n(50),i={statics:{keyHandlingOptions:{values:{38:function(e){e.setCurve(e.curve.raise()),e.redraw()},40:function(e){e.setCurve(i.lower(e)),e.redraw()}}}},lower:function(e){var t=e.curve,n=t.points,s=n.length,d=[],l;for(l=0;lr;r++)t.push({x:n/2+20*Math.random()+g(2*l*r/10)*(n/2-40),y:a/2+20*Math.random()+s(2*l*r/10)*(a/2-40)});var o=new e.Bezier(t);e.setCurve(o)},draw:function(e,n){e.reset();var a=n.points;this.setState({order:a.length});for(var r=a[0],o=0,s;1>=o;o+=.01){for(s=JSON.parse(JSON.stringify(a));1e.steps&&(e.steps=1)}}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t),e.steps=3},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.steps=5},drawFlattened:function(e,n){e.reset(),e.setColor("#DDD"),e.drawSkeleton(n),e.setColor("#DDD"),e.drawCurve(n);for(var a=1/e.steps,i=n.points[0],r=a,o;r<1+a;r+=a)o=n.get(d(r,1)),e.setColor("red"),e.drawLine(i,o),i=o;e.setFill("black"),e.text("Curve approximation using "+e.steps+" segments",{x:10,y:15})},values:{38:1,40:-1},onKeyDown:function(t,e){var n=this.values[t.keyCode];n&&(t.preventDefault(),e.steps+=n,1>e.steps&&(e.steps=1))}}},function(e,t,n){"use strict";var a=n(167),i=n(0),r=n(10);e.exports=r(i("flattening",a))},function(e){"use strict";e.exports={setup:function(e){e.setCurve(new e.Bezier([{x:90,y:110},{x:25,y:40},{x:230,y:40},{x:150,y:240}]))},draw:function(e,n){if(e.reset(),e.drawSkeleton(n),e.drawCurve(n),e.hover){e.setColor("rgb(200,100,100)");for(var a=e.getPanelWidth(),r=e.hover.x/a,o=e.drawHull(n,r),s=4;8>=s;s++)e.drawCircle(o[s],3);var d=n.get(r);e.drawCircle(d,5),e.setFill("black"),e.drawCircle(d,3);var l=0|100*r;r=l/100,e.text("Sequential interpolation for "+l+"% (t="+r+")",{x:10,y:15})}}}},function(e,t,n){"use strict";var a=n(169),i=n(0);e.exports=i("decasteljau",a)},function(e,t,n){"use strict";var a=n(0);e.exports=a("matrix")},function(e){"use strict";e.exports={setupQuadratic:function(e){var t=new e.Bezier(70,155,20,110,100,75);e.setCurve(t)},setupCubic:function(e){var t=new e.Bezier(60,105,75,30,215,115,140,160);e.setCurve(t)},draw:function(e,n){e.reset(),e.drawSkeleton(n),e.drawCurve(n),e.setColor("lightgrey");var a=.05,i=n.get(-10-a),r,o;for(r=-10;r<=a;r+=a)o=n.get(r),e.drawLine(i,o),i=o;i=n.get(1);for(r=1+a;r<=10;r+=a)o=n.get(r),e.drawLine(i,o),i=o}}},function(e,t,n){"use strict";var a=n(172),i=n(0);e.exports=i("extended",a)},function(e){"use strict";var t;e.exports={drawCubic:function(e){var t=new e.Bezier(120,160,35,200,220,260,220,40);e.setCurve(t)},drawCurve:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t)},setRatio:function(e,n){t=n,this.update(e)},changeRatio:function(e,n,a){t[a]=parseFloat(n)||1e-5,this.update(e)},update:function(e){e.curve.setRatios(t.slice()),this.drawCurve(e,e.curve)}}},function(e,t,n){"use strict";var a=n(174),i=n(0);e.exports=i("weightcontrol",a)},function(e){"use strict";e.exports={drawCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},drawCurve:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t)},drawFunction:function(e,t,n,a){e.setRandomColor(),e.drawFunction(a),e.setFill(e.getColor()),t&&e.text(t,n)},drawLerpBox:function(e,t,n,a){e.noColor(),e.setFill("rgba(0,0,100,0.2)");var i={x:a.x-5,y:n},r={x:a.x+5,y:t};e.drawRect(i,r),e.setColor("black")},drawLerpPoint:function(e,t,n,a,i){i.y=n+t*a,e.drawCircle(i,3),e.setFill("black"),e.text((0|1e4*t)/100+"%",{x:i.x+10,y:i.y+4}),e.noFill()},drawQuadraticLerp:function(e){e.reset();var n=e.getPanelWidth(),a=n-40;e.drawAxes(20,"t",0,1,"S","0%","100%");var i=e.hover;if(i&&i.x>=20&&i.x<=n-20){this.drawLerpBox(e,n,20,i);var r=(i.x-20)/a;this.drawLerpPoint(e,(1-r)*(1-r),20,a,i),this.drawLerpPoint(e,2*(1-r)*r,20,a,i),this.drawLerpPoint(e,r*r,20,a,i)}this.drawFunction(e,"first term",{x:40,y:a},function(e){return{x:20+e*a,y:20+a*(1-e)*(1-e)}}),this.drawFunction(e,"second term",{x:n/2-30,y:n/2+20},function(e){return{x:20+e*a,y:20+2*a*(1-e)*e}}),this.drawFunction(e,"third term",{x:a-50,y:a},function(e){return{x:20+e*a,y:20+a*e*e}})},drawCubicLerp:function(e){e.reset();var n=e.getPanelWidth(),a=n-40;e.drawAxes(20,"t",0,1,"S","0%","100%");var i=e.hover;if(i&&i.x>=20&&i.x<=n-20){this.drawLerpBox(e,n,20,i);var r=(i.x-20)/a;this.drawLerpPoint(e,(1-r)*(1-r)*(1-r),20,a,i),this.drawLerpPoint(e,3*(1-r)*(1-r)*r,20,a,i),this.drawLerpPoint(e,3*(1-r)*r*r,20,a,i),this.drawLerpPoint(e,r*r*r,20,a,i)}this.drawFunction(e,"first term",{x:40,y:a},function(e){return{x:20+e*a,y:20+a*(1-e)*(1-e)*(1-e)}}),this.drawFunction(e,"second term",{x:n/2-80,y:n/2},function(e){return{x:20+e*a,y:20+3*a*(1-e)*(1-e)*e}}),this.drawFunction(e,"third term",{x:n/2+40,y:n/2},function(e){return{x:20+e*a,y:20+3*a*(1-e)*e*e}}),this.drawFunction(e,"fourth term",{x:a-50,y:a},function(e){return{x:20+e*a,y:20+a*e*e*e}})},draw15thLerp:function(e){e.reset();var a=e.getPanelWidth(),i=a-40;e.drawAxes(20,"t",0,1,"S","0%","100%");var o=[1,15,105,455,1365,3003,5005,6435,6435,5005,3003,1365,455,105,15,1],s=e.hover,d;if(s&&s.x>=20&&s.x<=a-20)for(this.drawLerpBox(e,a,20,s),d=0;15>=d;d++){var l=(s.x-20)/i,t=o[d]*r(1-l,15-d)*r(l,d);this.drawLerpPoint(e,t,20,i,s)}for(d=0;15>=d;d++){var c=!1,u=!1;0===d&&(c="first term",u={x:25,y:i}),15===d&&(c="last term",u={x:a-70,y:i}),this.drawFunction(e,c,u,function(e){return{x:20+e*i,y:20+i*o[d]*r(1-e,15-d)*r(e,d)}})}}}},function(e,t,n){"use strict";var a=n(176),i=n(0);e.exports=i("control",a)},function(e){e.exports=function(){}},function(e){"use strict";e.exports={statics:{keyHandlingOptions:{propName:"step",values:{38:.1,40:-.1},controller:function(e){.1>e.step&&(e.step=.1)}}},setup:function(e){e.step=5},draw:function(e){var n=e.getPanelWidth(),a=n,i=n,r=a/2,d=i/2,l=r/2,c=d/2;e.reset(),e.setColor("black"),e.drawLine({x:0,y:d},{x:a,y:d}),e.drawLine({x:r,y:0},{x:r,y:i});for(var u={x:r,y:d},h=0,m;h<=e.step;h+=.1){m={x:l*g(h),y:c*s(h)},e.drawPoint(m,u);var f=h%1;(.05>f||.95=r)return null;return a.createElement("div",{key:"knot"+s},e,a.createElement("input",{type:"range",min:e,max:n,step:1,value:o,onChange:function(n){var e=t.state.weights;e[s]=n.target.value,i&&sa)throw new Error("degree must be at least 1 (linear)");if(a>p-1)throw new Error("degree must be less than or equal to point count - 1");if(!c)for(c=[],d=0;db)throw new Error("out of bounds");for(g=w[0];g=o[g]&&e<=o[g+1]);g++);var x=[];for(d=0;dg-a-1+f;d--)for(v=(e-o[d])/(o[d+a+1-f]-o[d]),m=0;mt.deltaY?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 n=this.ctx,a=!!(0o;o+=.01)i=r(o,this.degree,e,this.knots,a),n.lineTo(i[0],i[1]);i=r(1,this.degree,e,this.knots,a),n.lineTo(i[0],i[1]),n.stroke(),n.closePath()},drawKnots:function(e){var t=this,n=this.knots,a=!!(0n.length-1-t.degree)){var i=r(o,t.degree,e,n,a,!1,!0);t.circle(i[0],i[1],3)}})},drawNodes:function(e){var t=this,n;this.stroke(150),this.nodes.forEach(function(a,o){try{n=r(a,t.degree,e,t.knots,!1,!1,!0),t.line(n[0],n[1],e[o][0],e[o++][1])}catch(t){console.error(t)}})},formKnots:function(e,t){if(t=!0===t,!t)return this.formUniformKnots(e);var n=e.length,a=[],r=n-this.degree,o;for(o=1;oe[t[1]]||n.push(a)}return n},formWeights:function(e){var t=[];return e.forEach(function(){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 a=e.x-t,i=e.y-n,r=u(a*a+i*i);return rt&&(this.weights[t]+=.1*e,0>this.weights[t]&&(this.weights[t]=0)),t=this.points.indexOf(this.cp,t+1),-1!==t&&this.weights.length>t&&(this.weights[t]+=.1*e,0>this.weights[t]&&(this.weights[t]=0)),this.redraw()}},setKeyboardValues:function(t){t.ctrlKey||t.metaKey||t.altKey||t.preventDefault(),this.key=t.key,this.keyCode=t.code},setMouseValues:function(t){var e=this.cvs.getBoundingClientRect();this.mouseX=t.clientX-e.left,this.mouseY=t.clientY-e.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.cvs.style.width=this.width+"px",this.cvs.style.height=this.height+"px",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;tn--||setTimeout(a,200))})(),a.disconnect()});a.observe(div,{childList:!0,subtree:!0}),comments=document.getElementById("comments"),comments.scrollIntoView()}else t()}}},function(e){e.exports=function(e){e=e.replace(/,/g," ").replace(/-/g," - ").replace(/-\s+/g,"-").replace(/([a-zA-Z])/g," $1 ");var t=e.replace(/([a-zA-Z])\s?/g,"|$1").split("|"),n=t.length,r=[],o=0,s=0,l=0,c=0,u=0,h=0,p=0,m=0,g="",f,w,v,b,_,E;for(f=1;fn&&(e=n),e},Ge=function(e){return 3<=e.length?Array.prototype.slice.call(e):e[0]},j=function(e){var t,n;for(e._clipped=!1,e._unclipped=e.slice(0),t=n=0;3>n;t=++n)3>t?((0>e[t]||255e[t]&&(e[t]=0),255e[t]&&(e[t]=0),1=e?12.92*e:1.055*Ee(e,1/2.4)-.055)},le=function(e){return e>E.t1?e*e*e:E.t2*(e-E.t0)},E={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},Ie=function(){var e,t,n,a,i,o,s,d;return a=Ge(arguments),n=a[0],t=a[1],e=a[2],i=De(n,t,e),o=i[0],s=i[1],d=i[2],[116*s-16,500*(o-s),200*(s-d)]},Oe=function(e){return .04045>=(e/=255)?e/12.92:Ee((e+.055)/1.055,2.4)},He=function(e){return e>E.t3?Ee(e,1/3):e/E.t2+E.t0},De=function(){var e,t,n,a,i,o,s;return a=Ge(arguments),n=a[0],t=a[1],e=a[2],n=Oe(n),t=Oe(t),e=Oe(e),i=He((.4124564*n+.3575761*t+.1804375*e)/E.Xn),o=He((.2126729*n+.7151522*t+.072175*e)/E.Yn),s=He((.0193339*n+.119192*t+.9503041*e)/E.Zn),[i,o,s]},F.lab=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["lab"]),function(){})},L.lab=de,v.prototype.lab=function(){return Ie(this._rgb)},A=function(e){var t,n,a,i,r,s,d,l,o,u,h;return e=function(){var t,n,a;for(a=[],n=0,t=e.length;n=n;t=++n)a.push(r[t]+e*(s[t]-r[t]));return a}(),F.lab.apply(F,n)}):3===e.length?(u=function(){var t,n,a;for(a=[],n=0,t=e.length;n=n;t=++n)a.push((1-e)*(1-e)*r[t]+2*(1-e)*e*s[t]+e*e*d[t]);return a}(),F.lab.apply(F,n)}):4===e.length?(h=function(){var t,n,a;for(a=[],n=0,t=e.length;n=n;t=++n)a.push((1-e)*(1-e)*(1-e)*r[t]+3*(1-e)*(1-e)*e*s[t]+3*(1-e)*e*e*d[t]+e*e*e*l[t]);return a}(),F.lab.apply(F,n)}):5===e.length&&(n=A(e.slice(0,3)),a=A(e.slice(2,5)),t=function(e){return .5>e?n(2*e):a(2*(e-.5))}),t},F.bezier=function(e){var t;return t=A(e),t.scale=function(){return F.scale(t)},t},F.cubehelix=function(e,t,n,i,o){var s,d,a;return null==e&&(e=300),null==t&&(t=-1.5),null==n&&(n=1),null==i&&(i=1),null==o&&(o=[0,1]),s=0,"array"===Ue(o)?d=o[1]-o[0]:(d=0,o=[o,o]),a=function(c){var u,p,m,f,w,y,v,x,_;return u=S*((e+120)/360+t*c),v=Ee(o[0]+d*c,i),y=0===s?n:n[0]+c*s,p=y*v*(1-v)/2,f=W(u),_=Ve(u),x=v+p*(-.14861*f+1.78277*_),w=v+p*(-.29227*f-.90649*_),m=v+p*(+1.97294*f),F(j([255*x,255*w,255*m]))},a.start=function(t){return null==t?e:(e=t,a)},a.rotations=function(e){return null==e?t:(t=e,a)},a.gamma=function(e){return null==e?i:(i=e,a)},a.hue=function(e){return null==e?n:(n=e,"array"===Ue(n)?(s=n[1]-n[0],0===s&&(n=n[1])):s=0,a)},a.lightness=function(e){return null==e?o:("array"===Ue(e)?(o=e,d=e[1]-e[0]):(o=[e,e],d=0),a)},a.scale=function(){return F.scale(a)},a.hue(n),a},F.random=function(){var e,t,n,a;for(t="0123456789abcdef",e="#",n=a=0;6>a;n=++a)e+=t.charAt(K(16*Math.random()));return new v(e)},I=[],te=function(e,t,n,a){var i,r,s,d;for(null==n&&(n=.5),null==a&&(a="rgb"),"object"!==Ue(e)&&(e=F(e)),"object"!==Ue(t)&&(t=F(t)),(s=0,r=I.length);s=e[3]?"rgb":void 0}}),L.lrgb=L.rgb,ie=function(e,t,n,a){var i,r;return i=e._rgb,r=t._rgb,new v(qe(Ee(i[0],2)*(1-n)+Ee(r[0],2)*n),qe(Ee(i[1],2)*(1-n)+Ee(r[1],2)*n),qe(Ee(i[2],2)*(1-n)+Ee(r[2],2)*n),a)},T=function(e){var t,n,a,i,r,s;for(n=1/e.length,s=[0,0,0,0],(i=0,a=e.length);in;)n+=360;for(;360<=n;)n-=360;w[p]=n}else w[p]/=s[p];return F(w,t).alpha(a/m)},Y=function(e){var t,n,i,o,s,d;if(e.match(/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/))return(4===e.length||7===e.length)&&(e=e.substr(1)),3===e.length&&(e=e.split(""),e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),d=parseInt(e,16),o=d>>16,i=255&d>>8,n=255&d,[o,i,n,1];if(e.match(/^#?([A-Fa-f0-9]{8})$/))return 9===e.length&&(e=e.substr(1)),d=parseInt(e,16),o=255&d>>24,i=255&d>>16,n=255&d>>8,t=je(100*((255&d)/255))/100,[o,i,n,t];if(null!=L.css&&(s=L.css(e)))return s;throw"unknown color: "+e},Te=function(e,t){var n,i,s,d,l,c,h;return null==t&&(t="rgb"),l=e[0],s=e[1],i=e[2],n=e[3],l=o(l),s=o(s),i=o(i),h=l<<16|s<<8|i,c="000000"+h.toString(16),c=c.substr(c.length-6),d="0"+je(255*n).toString(16),d=d.substr(d.length-2),"#"+function(){switch(t.toLowerCase()){case"rgba":return c+d;case"argb":return d+c;default:return c;}}()},L.hex=function(e){return Y(e)},F.hex=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["hex"]),function(){})},v.prototype.hex=function(e){return null==e&&(e="rgb"),Te(this._rgb,e)},N.push({p:4,test:function(e){if(1===arguments.length&&"string"===Ue(e))return"hex"}}),$=function(){var e,t,n,a,d,u,p,m,f,w,y,v,x,_;if(e=Ge(arguments),d=e[0],y=e[1],p=e[2],0===y)f=a=t=255*p;else{for(_=[0,0,0],n=[0,0,0],x=.5>p?p*(1+y):p+y-p*y,v=2*p-x,d/=360,_[0]=d+1/3,_[1]=d,_[2]=d-1/3,u=m=0;2>=m;u=++m)0>_[u]&&(_[u]+=1),1<_[u]&&(_[u]-=1),n[u]=1>6*_[u]?v+6*(x-v)*_[u]:1>2*_[u]?x:2>3*_[u]?v+6*((x-v)*(2/3-_[u])):v;w=[je(255*n[0]),je(255*n[1]),je(255*n[2])],f=w[0],a=w[1],t=w[2]}return 3i?(ye-o)/(ye+o):(ye-o)/(2-ye-o),e===ye?a=(t-n)/(ye-o):t===ye?a=2+(n-e)/(ye-o):n===ye&&(a=4+(e-t)/(ye-o)),a*=60,0>a&&(a+=360),[a,u,i]},F.hsl=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["hsl"]),function(){})},L.hsl=$,v.prototype.hsl=function(){return Pe(this._rgb)},ee=function(){var e,n,a,o,d,l,c,u,m,w,y,x,_,E,C,k,S,T;return e=Ge(arguments),d=e[0],k=e[1],T=e[2],T*=255,(0===k?m=o=n=T:(360===d&&(d=0),360d&&(d+=360),d/=60,l=K(d),a=d-l,c=T*(1-k),u=T*(1-k*a),S=T*(1-k*(1-a)),0===l?(w=[T,S,c],m=w[0],o=w[1],n=w[2]):1===l?(y=[u,T,c],m=y[0],o=y[1],n=y[2]):2===l?(x=[c,T,S],m=x[0],o=x[1],n=x[2]):3===l?(_=[c,u,T],m=_[0],o=_[1],n=_[2]):4===l?(E=[S,c,T],m=E[0],o=E[1],n=E[2]):5===l?(C=[T,c,u],m=C[0],o=C[1],n=C[2]):void 0),[m,o,n,3a&&(a+=360)),[a,c,u]},F.hsv=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["hsv"]),function(){})},L.hsv=ee,v.prototype.hsv=function(){return Le(this._rgb)},xe=function(e){var t,n,a;return"number"===Ue(e)&&0<=e&&16777215>=e?(a=e>>16,n=255&e>>8,t=255&e,[a,n,t,1]):(console.warn("unknown num color: "+e),[0,0,0,1])},Ae=function(){var e,t,n,a;return a=Ge(arguments),n=a[0],t=a[1],e=a[2],(n<<16)+(t<<8)+e},F.num=function(e){return new v(e,"num")},v.prototype.num=function(e){return null==e&&(e="rgb"),Ae(this._rgb,e)},L.num=xe,N.push({p:1,test:function(e){if(1===arguments.length&&"number"===Ue(e)&&0<=e&&16777215>=e)return"num"}}),Q=function(){var e,n,a,o,s,d,l,u,m,w,y,x,_,E,C,k,S,T,N,P;return a=Ge(arguments),u=a[0],s=a[1],n=a[2],s/=100,l=255*(l/100),e=255*s,(0===s?x=l=o=n:(360===u&&(u=0),360u&&(u+=360),u/=60,m=K(u),d=u-m,w=n*(1-s),y=w+e*(1-d),N=w+e*d,P=w+e,0===m?(_=[P,N,w],x=_[0],l=_[1],o=_[2]):1===m?(E=[y,P,w],x=E[0],l=E[1],o=E[2]):2===m?(C=[w,P,N],x=C[0],l=C[1],o=C[2]):3===m?(k=[w,y,P],x=k[0],l=k[1],o=k[2]):4===m?(S=[N,w,P],x=S[0],l=S[1],o=S[2]):5===m?(T=[P,w,y],x=T[0],l=T[1],o=T[2]):void 0),[x,l,o,3o&&(o+=360)),[o,n,e]},F.hcg=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["hcg"]),function(){})},L.hcg=Q,v.prototype.hcg=function(){return Se(this._rgb)},U=function(e){var t,n,a,r,s,d,l,c;if(e=e.toLowerCase(),null!=F.colors&&F.colors[e])return Y(F.colors[e]);if(s=e.match(/rgb\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)/)){for(l=s.slice(1,4),r=d=0;2>=d;r=++d)l[r]=+l[r];l[3]=1}else if(s=e.match(/rgba\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*,\s*([01]|[01]?\.\d+)\)/))for(l=s.slice(1,5),r=c=0;3>=c;r=++c)l[r]=+l[r];else if(s=e.match(/rgb\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/)){for(l=s.slice(1,4),r=t=0;2>=t;r=++t)l[r]=je(2.55*l[r]);l[3]=1}else if(s=e.match(/rgba\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/)){for(l=s.slice(1,5),r=n=0;2>=n;r=++n)l[r]=je(2.55*l[r]);l[3]=+l[3]}else(s=e.match(/hsl\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/))?(a=s.slice(1,4),a[1]*=.01,a[2]*=.01,l=$(a),l[3]=1):(s=e.match(/hsla\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/))&&(a=s.slice(1,4),a[1]*=.01,a[2]*=.01,l=$(a),l[3]=+s[4]);return l},ke=function(e){var t;return(t=1>e[3]?"rgba":"rgb","rgb"===t)?t+"("+e.slice(0,3).map(je).join(",")+")":"rgba"===t?t+"("+e.slice(0,3).map(je).join(",")+","+e[3]+")":void 0},Re=function(e){return je(100*e)/100},J=function(e,t){var n;return n=1>t?"hsla":"hsl",e[0]=Re(e[0]||0),e[1]=Re(100*e[1])+"%",e[2]=Re(100*e[2])+"%","hsla"===n&&(e[3]=t),n+"("+e.join(",")+")"},L.css=function(e){return U(e)},F.css=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["css"]),function(){})},v.prototype.css=function(e){return(null==e&&(e="rgb"),"rgb"===e.slice(0,3))?ke(this._rgb):"hsl"===e.slice(0,3)?J(this.hsl(),this.alpha()):void 0},L.named=function(e){return Y(Xe[e])},N.push({p:5,test:function(e){if(1===arguments.length&&null!=Xe[e])return"named"}}),v.prototype.name=function(e){var t,n;for(n in arguments.length&&(Xe[e]&&(this._rgb=Y(Xe[e])),this._rgb[3]=1,this),t=this.hex(),Xe)if(t===Xe[n])return n;return t},ce=function(){var e,t,n,a;return a=Ge(arguments),n=a[0],e=a[1],t=a[2],t*=b,[n,W(t)*e,Ve(t)*e]},ue=function(){var e,t,n,i,o,s,d,u,p,m,f;return n=Ge(arguments),u=n[0],o=n[1],d=n[2],m=ce(u,o,d),e=m[0],t=m[1],i=m[2],f=de(e,t,i),p=f[0],s=f[1],i=f[2],[p,s,i,3o?1/(1-o):0,n=(1-d-o)*a,s=(1-i-o)*a,u=(1-t-o)*a,[n,s,u,o]},V=function(){var e,t,n,a,i,o,s,d,l;return(t=Ge(arguments),a=t[0],s=t[1],l=t[2],o=t[3],e=4=n;e=++n)a[e]*=255;return a},F.gl=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["gl"]),function(){})},v.prototype.gl=function(){var e;return e=this._rgb,[e[0]/255,e[1]/255,e[2]/255,e[3]]},Be=function(e,t,n){var a;return a=Ge(arguments),e=a[0],t=a[1],n=a[2],e=fe(e),t=fe(t),n=fe(n),.2126*e+.7152*t+.0722*n},fe=function(e){return e/=255,.03928>=e?e/12.92:Ee((e+.055)/1.055,2.4)},oe=function(e,t,n,a){var i,r;return i=e._rgb,r=t._rgb,new v(i[0]+n*(r[0]-i[0]),i[1]+n*(r[1]-i[1]),i[2]+n*(r[2]-i[2]),a)},I.push(["rgb",oe]),v.prototype.luminance=function(e,t){var n,a,i,r,o;return(null==t&&(t="rgb"),!arguments.length)?Be(this._rgb):(r=this._rgb,0===e?r=[0,0,0,this._rgb[3]]:1===e?r=[255,255,255,this[3]]:(n=Be(this._rgb),a=1e-7,i=20,o=function(n,r){var s,d;return d=n.interpolate(r,.5,t),s=d.luminance(),_(e-s)e?o(n,d):o(d,r)},r=n>e?o(F("black"),this).rgba():o(this,F("white")).rgba()),F(r).alpha(this.alpha()))},We=function(e){var t,n,a,i;return i=e/100,66>i?(a=255,n=-155.25485562709179-.44596950469579133*(n=i-2)+104.49216199393888*ge(n),t=20>i?0:-254.76935184120902+.8274096064007395*(t=i-10)+115.67994401066147*ge(t)):(a=351.97690566805693+.114206453784165*(a=i-55)-40.25366309332127*ge(a),n=325.4494125711974+.07943456536662342*(n=i-50)-28.0852963507957*ge(n),t=255),[a,n,t]},Me=function(){var e,t,n,a,i,o,s,d,l;for(s=Ge(arguments),o=s[0],n=s[1],e=s[2],i=1e3,a=4e4,t=.4;a-i>t;)l=.5*(a+i),d=We(l),d[2]/d[0]>=e/o?a=l:i=l;return je(l)},F.temperature=F.kelvin=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["temperature"]),function(){})},L.temperature=L.kelvin=L.K=We,v.prototype.temperature=function(){return Me(this._rgb)},v.prototype.kelvin=v.prototype.temperature,F.contrast=function(e,t){var n,i,r,o;return("string"===(r=Ue(e))||"number"===r)&&(e=new v(e)),("string"===(o=Ue(t))||"number"===o)&&(t=new v(t)),n=e.luminance(),i=t.luminance(),n>i?(n+.05)/(i+.05):(i+.05)/(n+.05)},F.distance=function(e,t,n){var r,o,s,l,c,h,p;for(o in null==n&&(n="lab"),("string"===(c=Ue(e))||"number"===c)&&(e=new v(e)),("string"===(h=Ue(t))||"number"===h)&&(t=new v(t)),s=e.get(n),l=t.get(n),p=0,s)r=(s[o]||0)-(l[o]||0),p+=r*r;return u(p)},F.deltaE=function(e,n,i,r){var o,s,d,l,c,u,h,p,m,g,w,y,_,E,k,S,T,N,P,I,A,M,D,O,R,j,F;for(null==i&&(i=1),null==r&&(r=1),("string"===(T=Ue(e))||"number"===T)&&(e=new v(e)),("string"===(N=Ue(n))||"number"===N)&&(n=new v(n)),P=e.lab(),o=P[0],d=P[1],c=P[2],I=n.lab(),s=I[0],l=I[1],u=I[2],h=qe(d*d+c*c),p=qe(l*l+u*u),D=16>o?.511:.040975*o/(1+.01765*o),A=.0638*h/(1+.0131*h)+.638,S=1e-6>h?0:180*B(c,d)/x;0>S;)S+=360;for(;360<=S;)S-=360;return O=164<=S&&345>=S?.56+z(.2*W(x*(S+168)/180)):.36+z(.4*W(x*(S+35)/180)),m=h*h*h*h,k=qe(m/(m+1900)),M=A*(k*O+1-k),E=o-s,_=h-p,w=d-l,y=c-u,g=w*w+y*y-_*_,R=E/(i*D),j=_/(r*A),F=M,qe(R*R+j*j+g/(F*F))},v.prototype.get=function(e){var t,n,a,r,o,s;return a=this,o=e.split("."),r=o[0],t=o[1],s=a[r](),t?(n=r.indexOf(t),-1t[1]&&(t[1]=0),F.lch(t).alpha(n.alpha())},v.prototype.desaturate=function(e){return null==e&&(e=1),this.saturate(-e)},v.prototype.premultiply=function(){var e,t;return t=this.rgb(),e=this.alpha(),F(t[0]*e,t[1]*e,t[2]*e,e)},M=function(e,t,n){if(!M[n])throw"unknown blend mode "+n;return M[n](e,t)},D=function(e){return function(t,n){var a,i;return a=F(n).rgb(),i=F(t).rgb(),F(e(a,i),"rgb")}},H=function(e){return function(t,n){var a,r,s;for(s=[],a=r=0;3>=r;a=++r)s[a]=e(t[a],n[a]);return s}},be=function(e){return e},ve=function(e,t){return e*t/255},G=function(e,t){return e>t?t:e},he=function(e,t){return e>t?e:t},Fe=function(e,t){return 255*(1-(1-e/255)*(1-t/255))},_e=function(e,t){return 128>t?2*e*t/255:255*(1-2*(1-e/255)*(1-t/255))},R=function(e,t){return 255*(1-(1-t/255)/(e/255))},X=function(e,t){return 255===e?255:(e=255*(t/255)/(1-e/255),255a.max&&(a.max=i),a.count+=1);return a.domain=[a.min,a.max],a.limits=function(e,t){return F.limits(a,e,t)},a},F.scale=function(e){var a,r,s,t,l,i,u,h,m,o,g,p,y,v,c,b,x,E,C,k,S,T,N;return o="rgb",g=F("#ccc"),c=0,i=!1,l=[0,1],v=[],y=[0,0],a=!1,s=[],p=!1,m=0,h=1,t=!1,r={},b=!0,u=1,T=function(e){var t,n,a,i,r,d;if(null==e&&(e=["#fff","#000"]),null!=e&&"string"===Ue(e)&&null!=F.brewer&&(e=F.brewer[e]||F.brewer[e.toLowerCase()]||e),"array"===Ue(e)){for(e=e.slice(0),t=a=0,i=e.length-1;0<=i?a<=i:a>=i;t=0<=i?++a:--a)n=e[t],"string"===Ue(n)&&(e[t]=F(n));for(v.length=0,t=d=0,r=e.length-1;0<=r?d<=r:d>=r;t=0<=r?++d:--d)v.push(t/(e.length-1))}return S(),s=e},C=function(e){var t,r;if(null!=a){for(r=a.length-1,t=0;t=a[t];)t++;return t-1}return 0},N=function(e){return e},x=function(e){var t,r,o,s,d;return d=e,2=P;_=0<=P?++S:--S){if(T=v[_],L<=T){x=s[_];break}if(L>=T&&_===v.length-1){x=s[_];break}if(L>T&&L=u;t=0<=u?++p:--p)v.push(t/(a-1));return l=[m,h],E},E.mode=function(e){return arguments.length?(o=e,S(),E):o},E.range=function(e,t){return T(e,t),E},E.out=function(e){return p=e,E},E.spread=function(e){return arguments.length?(c=e,E):c},E.correctLightness=function(e){return null==e&&(e=!0),t=e,S(),N=t?function(e){var n,a,i,r,o,s,d,l,c;for(n=k(0,!0).lab()[0],a=k(1,!0).lab()[0],d=n>a,i=k(e,!0).lab()[0],o=n+(a-n)*e,r=i-o,l=0,c=1,s=20;.01<_(r)&&0r?(l=e,e+=.5*(c-e)):(c=e,e+=.5*(l-e)),i=k(e,!0).lab()[0],r=i-o})();return e}:function(e){return e},E},E.padding=function(e){return null==e?y:("number"===Ue(e)&&(e=[e,e]),y=e,E)},E.colors=function(t,n){var r,o,d,c,u,h,p,m;if(2>arguments.length&&(n="hex"),u=[],0===arguments.length)u=s.slice(0);else if(1===t)u=[E(.5)];else if(1t;0<=t?e++:e--)h.push(e);return h}.apply(this).map(function(e){return E(o+e/(t-1)*r)});else{if(e=[],p=[],a&&2c;d=1<=c?++m:--m)p.push(.5*(a[d-1]+a[d]));else p=l;u=p.map(function(e){return E(e)})}return F[n]&&(u=u.map(function(e){return e[n]()})),u},E.cache=function(e){return null==e?b:(b=e,E)},E.gamma=function(e){return null==e?u:(u=e,E)},E},null==F.scales&&(F.scales={}),F.scales.cool=function(){return F.scale([F.hsl(180,1,.9),F.hsl(250,.7,.4)])},F.scales.hot=function(){return F.scale(["#000","#f00","#ff0","#fff"],[0,.25,.75,1]).mode("rgb")},F.analyze=function(e,t,n){var a,i,s,d,l,c,u;if(l={min:p,max:-1*p,sum:0,values:[],count:0},null==n&&(n=function(){return!0}),a=function(e){null==e||isNaN(e)||(l.values.push(e),l.sum+=e,el.max&&(l.max=e),l.count+=1)},u=function(e,i){if(n(e,i))return null!=t&&"function"===Ue(t)?a(t(e)):null!=t&&"string"===Ue(t)||"number"===Ue(t)?a(e[t]):a(e)},"array"===Ue(e))for(d=0,s=e.length;d=H;P=1<=H?++W:--W)B.push(M+P/a*(ye-M));B.push(ye)}else if("l"===t.substr(0,1)){if(0>=M)throw"Logarithmic scales are only possible for values > 0";for(D=r*ge(M),A=r*ge(ye),B.push(M),(P=ve=1,Q=a-1);1<=Q?ve<=Q:ve>=Q;P=1<=Q?++ve:--ve)B.push(Ee(10,D+P/a*(A-D)));B.push(ye)}else if("q"===t.substr(0,1)){for(B.push(M),P=s=1,te=a-1;1<=te?s<=te:s>=te;P=1<=te?++s:--s)U=(we.length-1)*P/a,G=K(U),G===U?B.push(we[G]):(X=U-G,B.push(we[G]*(1-X)+we[G+1]*X));B.push(ye)}else if("k"===t.substr(0,1)){for(R=we.length,E=Array(R),T=Array(a),ce=!0,V=0,k=null,k=[],k.push(M),(P=d=1,ne=a-1);1<=ne?d<=ne:d>=ne;P=1<=ne?++d:--d)k.push(M+P/a*(ye-M));for(k.push(ye);ce;){for(L=l=0,ie=a-1;0<=ie?l<=ie:l>=ie;L=0<=ie?++l:--l)T[L]=0;for(P=c=0,re=R-1;0<=re?c<=re:c>=re;P=0<=re?++c:--c){for(fe=we[P],O=p,(L=u=0,oe=a-1);0<=oe?u<=oe:u>=oe;L=0<=oe?++u:--u)N=z(k[L]-fe),N=se;L=0<=se?++h:--h)q[L]=null;for(P=m=0,de=R-1;0<=de?m<=de:m>=de;P=0<=de?++m:--m)S=E[P],null===q[S]?q[S]=we[P]:q[S]+=we[P];for(L=g=0,le=a-1;0<=le?g<=le:g>=le;L=0<=le?++g:--g)q[L]*=1/T[L];for(ce=!1,L=f=0,Y=a-1;0<=Y?f<=Y:f>=Y;L=0<=Y?++f:--f)if(q[L]!==k[P]){ce=!0;break}k=q,V++,200=Z;L=0<=Z?++y:--y)I[L]=[];for(P=b=0,J=R-1;0<=J?b<=J:b>=J;P=0<=J?++b:--b)S=E[P],I[S].push(we[P]);for(he=[],L=x=0,$=a-1;0<=$?x<=$:x>=$;L=0<=$?++x:--x)he.push(I[L][0]),he.push(I[L][I[L].length-1]);for(he=he.sort(function(e,t){return e-t}),B.push(he[0]),(P=_=1,ee=he.length-1);_<=ee;P=_+=2)pe=he[P],isNaN(pe)||-1!==B.indexOf(pe)||B.push(pe)}return B},Z=function(e,t,n){var a,o,d,l;return a=Ge(arguments),e=a[0],t=a[1],n=a[2],isNaN(e)&&(e=0),e/=360,e<1/3?(o=(1-t)/3,l=(1+t*W(S*e)/W(C-S*e))/3,d=1-(o+l)):e<2/3?(e-=1/3,l=(1-t)/3,d=(1+t*W(S*e)/W(C-S*e))/3,o=1-(l+d)):(e-=2/3,d=(1-t)/3,o=(1+t*W(S*e)/W(C-S*e))/3,l=1-(d+o)),l=pe(3*(n*l)),d=pe(3*(n*d)),o=pe(3*(n*o)),[255*l,255*d,255*o,3t&&(n=S-n),n/=S),[360*n,f,a]},F.hsi=function(){return function(e,t,n){n.prototype=e.prototype;var a=new n,i=e.apply(a,t);return Object(i)===i?i:a}(v,f.call(arguments).concat(["hsi"]),function(){})},L.hsi=Z,v.prototype.hsi=function(){return Ne(this._rgb)},ne=function(e,t,n,a){var i,r,o,s,d,l,c,u,h,p,g,f,w;return"hsl"===a?(f=e.hsl(),w=t.hsl()):"hsv"===a?(f=e.hsv(),w=t.hsv()):"hcg"===a?(f=e.hcg(),w=t.hcg()):"hsi"===a?(f=e.hsi(),w=t.hsi()):("lch"==a||"hcl"==a)&&(a="hcl",f=e.hcl(),w=t.hcl()),"h"===a.substr(0,1)&&(o=f[0],p=f[1],l=f[2],s=w[0],g=w[1],c=w[2]),isNaN(o)||isNaN(s)?isNaN(o)?isNaN(s)?r=y:(r=s,(1===l||0===l)&&"hsv"!==a&&(h=g)):(r=o,(1===c||0===c)&&"hsv"!==a&&(h=p)):(i=s>o&&180_(t.mx-e.x)&&10>_(t.my-e.y)&&(t.movingPoint=!0,t.mp=e,t.mp_idx=n,t.cx=e.x,t.cy=e.y)}),this.props.onMouseDown&&this.props.onMouseDown(e,this),"setCapture"in e.target&&e.target.setCapture()},mouseMove:function(e){if(!this.props.static){this.down&&(this.dragging=!0);var t=!1;if(this.lpts.forEach(function(n){var a=e.offsetX,i=e.offsetY;10>_(a-n.x)&&10>_(i-n.y)&&(t=t||!0)}),this.cvs.style.cursor=t?this.noDrag?"default":"pointer":"default",this.hover={x:e.offsetX,y:e.offsetY},this.noDrag||!this.movingPoint)this.mx=e.offsetX,this.my=e.offsetY;else if(this.ox=e.offsetX-this.mx,this.oy=e.offsetY-this.my,this.mp.x=w(0,d(this.defaultWidth,this.cx+this.ox)),this.mp.y=w(0,d(this.defaultHeight,this.cy+this.oy)),this.curve.forEach){for(var n=0,a,r;n=a)return o&&(e.__index=s+1),l&&n&&n.clone?l.clone():l;if(l=S.create(r),o&&(l.__read=!0),l=l.initialize.apply(l,0e.length&&(n=e.length);for(var s=0;sthis.precision?o(e*this.multiplier)/this.multiplier:e},pair:function(e,t,n){return this.number(e)+(n||",")+this.number(t)},point:function(e,t){return this.number(e.x)+(t||",")+this.number(e.y)},size:function(e,t){return this.number(e.width)+(t||",")+this.number(e.height)},rectangle:function(e,t){return this.point(e,t)+(t||",")+this.size(e,t)}});P.instance=new P;var L=new function(){function l(e,t,n){return en?n:e}function t(e,t,n){function a(e){var t=134217729*e,n=e-t+t;return[n,e-n]}var r=t*t-e*n;if(3*i(r)e||1e8=-m&&e<=m},clamp:l,integrate:function(e,t,a,r){for(var n=s[r-2],o=d[r-2],l=.5*(a-t),c=l+t,u=0,h=1&r?o[u++]*e(c):0,p;u>1;)p=l*n[u],h+=o[u++]*(e(c+p)+e(c-p));return l*h},findRoot:function(e,t,r,o,s,d,n){for(var c=0;c=s?.5*(o+s):p)}return l(r,o,s)},solveQuadratic:function(e,r,o,s,d,u){var p=1/0,w;if(i(e)=-g){var f=0>y?0:h(y),x=r+(0>r?-f:f);0===x?(w=o/e,p=-w):(w=x/e,p=o/x)}}var _=0,E=null==d,C=d-m,k=u+m;return isFinite(w)&&(E||w>C&&wC&&pI?-1:1,s=-N/e,z=0r*f);i(e)*f*f>i(y/f)&&(T=-y/f,S=(T-u)/f)}}var A=L.solveQuadratic(e,S,T,v,_,E),M=null==_;return isFinite(f)&&(0===A||0_-m&&fn?-1:1e?-1:1)&&0<=this.y*(2c&&(d=h.x,c=-c),0>u&&(l=h.y,u=-u)}else{var p=A.read(arguments);c=p.width,u=p.height}this._set(d,l,c,u),r=arguments.__index;var m=arguments.__filtered;m&&(this.__filtered=m)}return this.__read&&(this.__read=r),this},set:"#initialize",_set:function(e,t,n,a){return this.x=e,this.y=t,this.width=n,this.height=a,this},clone:function(){return new D(this.x,this.y,this.width,this.height)},equals:function(e){var t=S.isPlainValue(e)?D.read(arguments):e;return t===this||t&&this.x===t.x&&this.y===t.y&&this.width===t.width&&this.height===t.height||!1},toString:function(){var e=P.instance;return"{ x: "+e.number(this.x)+", y: "+e.number(this.y)+", width: "+e.number(this.width)+", height: "+e.number(this.height)+" }"},_serialize:function(e){var t=e.formatter;return[t.number(this.x),t.number(this.y),t.number(this.width),t.number(this.height)]},getPoint:function(e){var t=e?B:z;return new t(this.x,this.y,this,"setPoint")},setPoint:function(){var e=B.read(arguments);this.x=e.x,this.y=e.y},getSize:function(e){var t=e?A:M;return new t(this.width,this.height,this,"setSize")},_fw:1,_fh:1,setSize:function(){var e=A.read(arguments),t=this._sx,n=this._sy,a=e.width,i=e.height;t&&(this.x+=(this.width-a)*t),n&&(this.y+=(this.height-i)*n),this.width=a,this.height=i,this._fw=this._fh=1},getLeft:function(){return this.x},setLeft:function(e){if(!this._fw){var t=e-this.x;this.width-=.5===this._sx?2*t:t}this.x=e,this._sx=this._fw=0},getTop:function(){return this.y},setTop:function(e){if(!this._fh){var t=e-this.y;this.height-=.5===this._sy?2*t:t}this.y=e,this._sy=this._fh=0},getRight:function(){return this.x+this.width},setRight:function(e){if(!this._fw){var t=e-this.x;this.width=.5===this._sx?2*t:t}this.x=e-this.width,this._sx=1,this._fw=0},getBottom:function(){return this.y+this.height},setBottom:function(e){if(!this._fh){var t=e-this.y;this.height=.5===this._sy?2*t:t}this.y=e-this.height,this._sy=1,this._fh=0},getCenterX:function(){return this.x+this.width/2},setCenterX:function(e){this._fw||.5===this._sx?this.x=e-this.width/2:(this._sx&&(this.x+=2*(e-this.x)*this._sx),this.width=2*(e-this.x)),this._sx=.5,this._fw=0},getCenterY:function(){return this.y+this.height/2},setCenterY:function(e){this._fh||.5===this._sy?this.y=e-this.height/2:(this._sy&&(this.y+=2*(e-this.y)*this._sy),this.height=2*(e-this.y)),this._sy=.5,this._fh=0},getCenter:function(e){var t=e?B:z;return new t(this.getCenterX(),this.getCenterY(),this,"setCenter")},setCenter:function(){var e=B.read(arguments);return this.setCenterX(e.x),this.setCenterY(e.y),this},getArea:function(){return this.width*this.height},isEmpty:function(){return 0===this.width||0===this.height},contains:function(e){return e&&void 0!==e.width||4===(Array.isArray(e)?e:arguments).length?this._containsRectangle(D.read(arguments)):this._containsPoint(B.read(arguments))},_containsPoint:function(e){var t=e.x,n=e.y;return t>=this.x&&n>=this.y&&t<=this.x+this.width&&n<=this.y+this.height},_containsRectangle:function(e){var t=e.x,n=e.y;return t>=this.x&&n>=this.y&&t+e.width<=this.x+this.width&&n+e.height<=this.y+this.height},intersects:function(){var e=D.read(arguments),t=S.read(arguments)||0;return e.x+e.width>this.x-t&&e.y+e.height>this.y-t&&e.xarguments.length?this._transformPoint(B.read(arguments)):this._transformCoordinates(e,t,n)},_transformPoint:function(e,t,n){var a=e.x,i=e.y;return t||(t=new B),t._set(a*this._a+i*this._c+this._tx,a*this._b+i*this._d+this._ty,n)},_transformCoordinates:function(e,t,n){for(var a=0;a<2*n;a+=2){var r=e[a],o=e[a+1];t[a]=r*this._a+o*this._c+this._tx,t[a+1]=r*this._b+o*this._d+this._ty}return t},_transformCorners:function(e){var t=e.x,n=e.y,a=t+e.width,i=n+e.height,r=[t,n,a,n,a,i,t,i];return this._transformCoordinates(r,r,4)},_transformBounds:function(e,t,n){for(var a=this._transformCorners(e),r=a.slice(0,2),o=r.slice(),s=2;8>s;s++){var d=a[s],l=1&s;do[l]&&(o[l]=d)}return t||(t=new D),t._set(r[0],r[1],o[0]-r[0],o[1]-r[1],n)},inverseTransform:function(){return this._inverseTransform(B.read(arguments))},_inverseTransform:function(e,t,n){var i=this._a,a=this._b,r=this._c,o=this._d,s=this._tx,d=this._ty,l=i*o-a*r,c=null;if(l&&!isNaN(l)&&isFinite(s)&&isFinite(d)){var u=e.x-this._tx,h=e.y-this._ty;t||(t=new B),c=t._set((u*o-h*r)/l,(h*i-u*a)/l,n)}return c},decompose:function(){var e=this._a,t=this._b,n=this._c,a=this._d,i=e*a-t*n,o=u,d=h,c=180/l,p,g,f;if(0!==e||0!==t){var w=o(e*e+t*t);p=m(e/w)*(0=p?0:1<=p?1:p),new B(e+p*n,t+p*a)}},getSide:function(e,t,n,a,i,r,o,s){o||(n-=e,a-=t);var d=i-e,l=d*a-(r-t)*n;return!s&&L.isZero(l)&&(l=(d*n+d*n)/(n*n+a*a),0<=l&&1>=l&&(l=0)),0>l?-1:0n?r-t:t-r:((i-e)*a-(r-t)*n)/u(n*n+a*a)},getDistance:function(e,t,n,a,i,r,o){return _(j.getSignedDistance(e,t,n,a,i,r,o))}}}),F=N.extend({_class:"Project",_list:"projects",_reference:"project",_compactSerialize:!0,initialize:function(e){N.call(this,!0),this._children=[],this._namedChildren={},this._activeLayer=null,this._currentStyle=new le(null,null,this),this._view=he.create(this,e||_e.getCanvas(1,1)),this._selectionItems={},this._selectionCount=0,this._updateVersion=0},_serialize:function(e,t){return S.serialize(this._children,e,!0,t)},_changed:function(e,t){if(1&e){var n=this._view;n&&(n._needsUpdate=!0,!n._requested&&n._autoUpdate&&n.requestUpdate())}var a=this._changes;if(a&&t){var i=this._changesById,r=t._id,o=i[r];o?o.flags|=e:a.push(i[r]={item:t,flags:e})}},clear:function(){for(var e=this._children,t=e.length-1;0<=t;t--)e[t].remove()},isEmpty:function(){return!this._children.length},remove:function e(){return!!e.base.call(this)&&(this._view&&this._view.remove(),!0)},getView:function(){return this._view},getCurrentStyle:function(){return this._currentStyle},setCurrentStyle:function(e){this._currentStyle.set(e)},getIndex:function(){return this._index},getOptions:function(){return this._scope.settings},getLayers:function(){return this._children},getActiveLayer:function(){return this._activeLayer||new W({project:this,insert:!0})},getSymbolDefinitions:function(){var e=[],t={};return this.getItems({class:X,match:function(n){var a=n._definition,i=a._id;return t[i]||(t[i]=!0,e.push(a)),!1}}),e},getSymbols:"getSymbolDefinitions",getSelectedItems:function(){var e=this._selectionItems,t=[];for(var n in e){var a=e[n],i=a._selection;1&i&&a.isInserted()?t.push(a):!i&&this._updateSelection(a)}return t},_updateSelection:function(e){var t=e._id,n=this._selectionItems;e._selection?n[t]!==e&&(this._selectionCount++,n[t]=e):n[t]===e&&(this._selectionCount--,delete n[t])},selectAll:function(){for(var e=this._children,t=0,n=e.length;t=e.subtract(a).divide(l).length)return new K(t,h,{name:n?S.hyphenate(n):t,point:a})}if(this._locked||!this._visible||this._guide&&!t.guides||this.isEmpty())return null;var o=this._matrix,s=n?n.appended(o):this.getGlobalMatrix().prepend(this.getView()._matrix),d=w(t.tolerance,1e-12),l=t._tolerancePadding=new A(ee._getStrokePadding(d,o._shiftless().invert()));if(e=o._inverseTransform(e),!e||!this._children&&!this.getBounds({internal:!0,stroke:!0,handle:!0}).expand(l.multiply(2))._containsPoint(e))return null;var c=!(t.guides&&!this._guide||t.selected&&!this.isSelected()||t.type&&t.type!==S.hyphenate(this._class)||t.class&&!(this instanceof t.class)),u=t.match,h=this,p=t.position,m=t.center,g=t.bounds,f,y;if(c&&this._parent&&(p||m||g)){if((m||g)&&(f=this.getInternalBounds()),y=p&&r("position")||m&&r("center","Center"),!y&&g)for(var v=["TopLeft","TopRight","BottomLeft","BottomRight","LeftCenter","TopCenter","RightCenter","BottomCenter"],b=0;8>b&&!y;b++)y=r("bounds",v[b]);y=a(y)}return y||(y=this._hitTestChildren(e,t,s)||c&&a(this._hitTestSelf(e,t,s,this.getStrokeScaling()?null:s._shiftless().invert()))||null),y&&y.point&&(y.point=o.transform(y.point)),y},_hitTestSelf:function(e,t){if(t.fill&&this.hasFill()&&this._contains(e))return new K("fill",this)},matches:function(e,t){function n(e,t){for(var a in e)if(e.hasOwnProperty(a)){var i=e[a],r=t[a];if(S.isPlainObject(i)&&S.isPlainObject(r)){if(!n(i,r))return!1;}else if(!S.equals(i,r))return!1}return!0}var a=typeof e;if("object"==a){for(var i in e)if(e.hasOwnProperty(i)&&!this.matches(i,e[i]))return!1;return!0}if("function"==a)return e(this);if("match"===e)return t(this);var r=/^(empty|editable)$/.test(e)?this["is"+S.capitalize(e)]():"type"===e?S.hyphenate(this._class):this[e];if("class"===e){if("function"==typeof t)return this instanceof t;r=this._class}if("function"==typeof t)return!!t(r);if(t){if(t.test)return t.test(r);if(S.isPlainObject(t))return n(t,r)}return S.equals(r,t)},getItems:function(e){return V._getItems(this,e,this._matrix)},getItem:function(e){return V._getItems(this,e,this._matrix,null,!0)[0]||null},statics:{_getItems:function e(t,n,a,r,o){if(!r){var s="object"==typeof n&&n,d=s&&s.overlapping,c=s&&s.inside,u=d||c,h=u&&D.read([u]);r={items:[],recursive:s&&!1!==s.recursive,inside:!!c,overlapping:!!d,rect:h,path:d&&new ee.Rectangle({rectangle:h,insert:!1})},s&&(n=S.filter({},n,{recursive:!0,inside:!0,overlapping:!0}))}var p=t._children,m=r.items,h=r.rect;a=h&&(a||new R);for(var g=0,f=p&&p.length;gi:al)&&this._canComposite(),p=t.pixelRatio||1,m,g,f;if(!h){var w=this.getStrokeBounds(r);if(!w.width||!w.height)return;f=t.offset,g=t.offset=w.getTopLeft().floor(),m=e,e=_e.getContext(w.getSize().ceil().add(1).multiply(p)),1!==p&&e.scale(p,p)}e.save();var y=n?n.appended(o):this._canScaleStroke&&!this.getStrokeScaling(!0)&&r,v=!h&&t.clipItem,b=!y||v;if(h?(e.globalAlpha=l,u&&(e.globalCompositeOperation=d)):b&&e.translate(-g.x,-g.y),b&&(h?o:r).applyToContext(e),v&&t.clipItem.draw(e,t.extend({clip:!0})),y){e.setTransform(p,0,0,p,0,0);var x=t.offset;x&&e.translate(-x.x,-x.y)}this._draw(e,t,r,y),e.restore(),i.pop(),t.clip&&!t.dontFinish&&e.clip(),h||(Ee.process(d,e,m,l,g.subtract(f).multiply(p)),_e.release(e),t.offset=f)}}},_isUpdated:function(e){var t=this._parent;if(t instanceof te)return t._isUpdated(e);var n=this._updateVersion===e;return!n&&t&&t._visible&&t._isUpdated(e)&&(this._updateVersion=e,n=!0),n},_drawSelection:function(e,t,n,a,r){var o=this._selection,s=1&o,d=2&o||s&&this._selectBounds,c=4&o;if(this._drawSelected||(s=!1),(s||d||c)&&this._isUpdated(r)){var u=this.getSelectedColor(!0)||(m=this.getLayer())&&m.getSelectedColor(!0),h=t.appended(this.getGlobalMatrix(!0)),p=n/2,m;if(e.strokeStyle=e.fillStyle=u?u.toCanvasStyle(e):"#009dec",s&&this._drawSelected(e,h,a),c){var g=this.getPosition(!0),f=g.x,w=g.y;e.beginPath(),e.arc(f,w,p,0,2*l,!0),e.stroke();for(var y=[[0,-1],[1,0],[0,1],[-1,0]],v=p,b=n+1,x=0;4>x;x++){var _=y[x],E=_[0],C=_[1];e.moveTo(f+E*v,w+C*v),e.lineTo(f+E*b,w+C*b),e.stroke()}}if(d){var k=h._transformCorners(this.getInternalBounds());e.beginPath();for(var x=0;8>x;x++)e[x?"lineTo":"moveTo"](k[x],k[++x]);e.closePath(),e.stroke();for(var x=0;8>x;x++)e.fillRect(k[x]-p,k[++x]-p,n,n)}}},_canComposite:function(){return!1}},S.each(["down","drag","up","move"],function(e){this["removeOn"+S.capitalize(e)]=function(){var t={};return t[e]=!0,this.removeOn(t)}},{removeOn:function(e){for(var t in e)if(e[t]){var n="mouse"+t,a=this._project,i=a._removeSets=a._removeSets||{};i[n]=i[n]||{},i[n][this._id]=this}return this}})),q=V.extend({_class:"Group",_selectBounds:!1,_selectChildren:!0,_serializeFields:{children:[]},initialize:function(e){this._children=[],this._namedChildren={},this._initialize(e)||this.addChildren(Array.isArray(e)?e:arguments)},_changed:function e(t){e.base.call(this,t),1026&t&&(this._clipItem=void 0)},_getClipItem:function(){var e=this._clipItem;if(void 0===e){e=null;for(var t=this._children,n=0,a=t.length;n=r;r++){var o=new B(1r?-1:1,2=i.subtract(i.normalize()).multiply(t).divide(n).length}return{_contains:function t(n){if("rectangle"===this._type){var a=e(this,n);return a?1>=n.subtract(a.point).divide(this._radius).getLength():t.base.call(this,n)}return .5>=n.divide(this.size).getLength()},_hitTestSelf:function n(a,i,r,o){var s=!1,d=this._style,l=i.stroke&&d.hasStroke(),c=i.fill&&d.hasFill();if(l||c){var u=this._type,h=this._radius,p=l?d.getStrokeWidth()/2:0,m=i._tolerancePadding.add(ee._getStrokePadding(p,!d.getStrokeScaling()&&o));if("rectangle"===u){var g=m.multiply(2),f=e(this,a,g);if(f)s=t(a.subtract(f.point),h,m,f.quadrant);else{var w=new D(this._size).setCenter(0,0),y=w.expand(g),v=w.expand(g.negate());s=y._containsPoint(a)&&!v._containsPoint(a)}}else s=t(a,h,m)}return s?new K(l?"stroke":"fill",this):n.base.apply(this,arguments)}}},{statics:new function(){function e(e,t,n,a,i){var r=new U(S.getNamed(i),t);return r._type=e,r._size=n,r._radius=a,r}return{Circle:function(){var t=B.readNamed(arguments,"center"),n=S.readNamed(arguments,"radius");return e("circle",t,new A(2*n),n,arguments)},Rectangle:function(){var t=D.readNamed(arguments,"rectangle"),n=A.min(A.readNamed(arguments,"radius"),t.getSize(!0).divide(2));return e("rectangle",t.getCenter(!0),t.getSize(!0),n,arguments)},Ellipse:function(){var t=U._readEllipse(arguments),n=t.radius;return e("ellipse",t.center,n.multiply(2),n,arguments)},_readEllipse:function(e){var t,n;if(S.hasNamed(e,"radius"))t=B.readNamed(e,"center"),n=A.readNamed(e,"radius");else{var a=D.readNamed(e,"rectangle");t=a.getCenter(!0),n=a.getSize(!0).divide(2)}return{center:t,radius:n}}}}}),G=V.extend({_class:"Raster",_applyMatrix:!1,_canApplyMatrix:!1,_boundsOptions:{stroke:!1,handle:!1},_serializeFields:{crossOrigin:null,source:null},_prioritize:["crossOrigin"],initialize:function(e,t){if(!this._initialize(e,void 0!==t&&B.read(arguments,1))){var n="string"==typeof e?C.getElementById(e):e;n?this.setImage(n):this.setSource(e)}this._size||(this._size=new A,this._loaded=!1)},_equals:function(e){return this.getSource()===e.getSource()},copyContent:function(e){var t=e._image,n=e._canvas;if(t)this._setImage(t);else if(n){var a=_e.getCanvas(e._size);a.getContext("2d").drawImage(n,0,0),this._setImage(a)}this._crossOrigin=e._crossOrigin},getSize:function(){var e=this._size;return new M(e?e.width:0,e?e.height:0,this,"setSize")},setSize:function(){var e=A.read(arguments);if(!e.equals(this._size))if(0g;g++)p[g]/=m;return m?oe.read(p):null},getPixel:function(){var e=B.read(arguments),t=this.getContext().getImageData(e.x,e.y,1,1).data;return new oe("rgb",[t[0]/255,t[1]/255,t[2]/255],t[3]/255)},setPixel:function(){var e=B.read(arguments),t=oe.read(arguments),n=t._convert("rgb"),a=t._alpha,i=this.getContext(!0),r=i.createImageData(1,1),o=r.data;o[0]=255*n[0],o[1]=255*n[1],o[2]=255*n[2],o[3]=null==a?255:255*a,i.putImageData(r,e.x,e.y)},createImageData:function(){var e=A.read(arguments);return this.getContext().createImageData(e.width,e.height)},getImageData:function(){var e=D.read(arguments);return e.isEmpty()&&(e=new D(this._size)),this.getContext().getImageData(e.x,e.y,e.width,e.height)},setImageData:function(e){var t=B.read(arguments,1);this.getContext(!0).putImageData(e,t.x,t.y)},_getBounds:function(e){var t=new D(this._size).setCenter(0,0);return e?e._transformBounds(t):t},_hitTestSelf:function(e){if(this._contains(e)){var t=this;return new K("pixel",t,{offset:e.add(t._size.divide(2)).round(),color:{get:function(){return t.getPixel(this.offset)}}})}},_draw:function(e){var t=this.getElement();t&&(e.globalAlpha=this._opacity,e.drawImage(t,-this._size.width/2,-this._size.height/2))},_canComposite:function(){return!0}}),X=V.extend({_class:"SymbolItem",_applyMatrix:!1,_canApplyMatrix:!1,_boundsOptions:{stroke:!0},_serializeFields:{symbol:null},initialize:function(e,t){this._initialize(e,void 0!==t&&B.read(arguments,1))||this.setDefinition(e instanceof H?e:new H(e))},_equals:function(e){return this._definition===e._definition},copyContent:function(e){this.setDefinition(e._definition)},getDefinition:function(){return this._definition},setDefinition:function(e){this._definition=e,this._changed(9)},getSymbol:"#getDefinition",setSymbol:"#setDefinition",isEmpty:function(){return this._definition._item.isEmpty()},_getBounds:function(e,t){var n=this._definition._item;return n._getCachedBounds(n._matrix.prepended(e),t)},_hitTestSelf:function(e,t,n){var a=this._definition._item._hitTest(e,t,n);return a&&(a.item=this),a},_draw:function(e,t){this._definition._item.draw(e,t)}}),H=S.extend({_class:"SymbolDefinition",initialize:function(e,t){this._id=I.get(),this.project=f.project,e&&this.setItem(e,t)},_serialize:function(e,t){return t.add(this,function(){return S.serialize([this._class,this._item],e,!1,t)})},_changed:function(e){8&e&&V._clearBoundsCache(this),1&e&&this.project._changed(e)},getItem:function(){return this._item},setItem:function(e,t){e._symbol&&(e=e.clone()),this._item&&(this._item._symbol=null),this._item=e,e.remove(),e.setSelected(!1),t||e.setPosition(new B),e._symbol=this,this._changed(9)},getDefinition:"#getItem",setDefinition:"#setItem",place:function(e){return new X(this,e)},clone:function(){return new H(this._item.clone(!1))},equals:function(e){return e===this||e&&this._item.equals(e._item)||!1}}),K=S.extend({_class:"HitResult",initialize:function(e,t,n){this.type=e,this.item=t,n&&this.inject(n)},statics:{getOptions:function(e){var t=e&&S.read(e);return S.set({type:null,tolerance:f.settings.hitTolerance,fill:!t,stroke:!t,segments:!t,handles:!1,ends:!1,position:!1,center:!1,bounds:!1,guides:!1,selected:!1},t)}}}),Q=S.extend({_class:"Segment",beans:!0,_selection:0,initialize:function(e,t,n,a,i,r){var o=arguments.length,s,d,l,c;0n;n+=2)t.push(new B(e[n],e[n+1]));return t}},{getLength:function(){return null==this._length&&(this._length=Z.getLength(this.getValues(),0,1)),this._length},getArea:function(){return Z.getArea(this.getValues())},getLine:function(){return new j(this._segment1._point,this._segment2._point)},getPart:function(e,t){return new Z(Z.getPart(this.getValues(),e,t))},getPartLength:function(e,t){return Z.getLength(this.getValues(),e,t)},divideAt:function(e){return this.divideAtTime(e&&e.curve===this?e.time:this.getTimeAt(e))},divideAtTime:function(e,t){var n=1e-8,a=null;if(e>=n&&e<=1-n){var i=Z.subdivide(this.getValues(),e),r=i[0],o=i[1],s=t||this.hasHandles(),d=this._segment1,l=this._segment2,c=this._path;s&&(d._handleOut._set(r[2]-r[0],r[3]-r[1]),l._handleIn._set(o[4]-o[6],o[5]-o[7]));var u=r[6],h=r[7],p=new Q(new B(u,h),s&&new B(r[4]-u,r[5]-h),s&&new B(o[2]-u,o[3]-h));c?(c.insert(d._index+1,p),a=this.getNext()):(this._segment2=p,this._changed(),a=new Z(p,l))}return a},splitAt:function(e){var t=this._path;return t?t.splitAt(e):null},splitAtTime:function(e){return this.splitAt(this.getLocationAtTime(e))},divide:function(e,t){return this.divideAtTime(void 0===e?.5:t?e:this.getTimeAt(e))},split:function(e,t){return this.splitAtTime(void 0===e?.5:t?e:this.getTimeAt(e))},reversed:function(){return new Z(this._segment2.reversed(),this._segment1.reversed())},clearHandles:function(){this._segment1._handleOut._set(0,0),this._segment2._handleIn._set(0,0)},statics:{getValues:function(e,t,n,a){var i=e._point,r=e._handleOut,o=t._handleIn,s=t._point,d=i.x,l=i.y,c=s.x,u=s.y,h=a?[d,l,d,l,c,u,c,u]:[d,l,d+r._x,l+r._y,c+o._x,u+o._y,c,u];return n&&n._transformCoordinates(h,h,4),h},subdivide:function(e,n){var a=e[0],i=e[1],r=e[2],o=e[3],s=e[4],d=e[5],l=e[6],c=e[7];void 0===n&&(n=.5);var h=1-n,u=h*a+n*r,p=h*i+n*o,m=h*r+n*s,g=h*o+n*d,f=h*s+n*l,w=h*d+n*c,y=h*u+n*m,v=h*p+n*g,b=h*m+n*f,x=h*g+n*w,_=h*y+n*b,E=h*v+n*x;return[[a,i,u,p,y,v,_,E],[_,E,b,x,f,w,l,c]]},getMonoCurves:function(e,a){var i=[],r=a?0:1,o=e[r+0],s=e[r+2],d=e[r+4],l=e[r+6];if(o>=s==s>=d&&s>=d==d>=l||Z.isStraight(e))i.push(e);else{var c=1e-8,u=[],h=L.solveQuadratic(3*(s-d)-o+l,2*(o+d)-4*s,s-o,u,c,1-c);if(!h)i.push(e);else{u.sort();var n=u[0],p=Z.subdivide(e,n);i.push(p[0]),1n&&l>n&&s>n&&d>n)){var h=3*(s-o),c=3*(d-s)-h;u=L.solveCubic(l-o-h-c,c,h,o-n,a,i,r)}return u},getTimeOf:function(e,n){var a=new B(e[0],e[1]),r=new B(e[6],e[7]),o=1e-12,s=1e-7,d=n.isClose(a,o)?0:n.isClose(r,o)?1:null;if(null===d)for(var t=[n.x,n.y],l=[],h=0,p;2>h;h++){p=Z.solveCubic(e,h,t[h],l,0,1);for(var m=0,g;m=a){var t=n.getDistance(Z.getPoint(e,a),!0);if(th?0:.999999999999n;if(a){var i=t;t=n,n=i}return 0n&&(e=Z.subdivide(e,(n-t)/(1-t))[0]),a?[e[6],e[7],e[4],e[5],e[2],e[3],e[0],e[1]]:e},isFlatEnough:function(e,t){var n=e[0],a=e[1],i=e[2],r=e[3],o=e[4],s=e[5],d=e[6],l=e[7],c=3*i-2*n-d,u=3*r-2*a-l,h=3*o-2*d-n,p=3*s-2*l-a;return w(c*c,h*h)+w(u*u,p*p)<=16*t*t},getArea:function(e){var t=e[0],n=e[1],a=e[2],i=e[3],r=e[4],o=e[5],s=e[6],d=e[7];return 3*((d-n)*(a+r)-(s-t)*(i+o)+i*(t-r)-a*(n-o)+d*(r+t/3)-s*(o+n/3))/20},getBounds:function(e){for(var t=e.slice(0,2),n=t.slice(),a=[0,0],r=0;2>r;r++)Z._addBounds(e[r],e[r+2],e[r+4],e[r+6],r,0,t,n,a);return new D(t[0],t[1],n[0]-t[0],n[1]-t[1])},_addBounds:function(e,n,a,r,o,s,d,l,c){function h(e,t){var n=e-t,a=e+t;nl[o]&&(l[o]=a)}s/=2;var p=d[o]-s,m=l[o]+s;if(em||n>m||a>m||r>m)if(n=d&&0>=l&&-1<=l}}return!1},isLinear:function(e,t,n,a){var i=a.subtract(e).divide(3);return t.equals(i)&&n.negate().equals(i)}},function(e,t){this[t]=function(t){var n=this._segment1,a=this._segment2;return e(n._point,n._handleOut,a._handleIn,a._point,t)},this.statics[t]=function(t,n){var a=t[0],i=t[1],r=t[6],o=t[7];return e(new B(a,i),new B(t[2]-a,t[3]-i),new B(t[4]-r,t[5]-o),new B(r,o),n)}},{statics:{},hasHandles:function(){return!this._segment1._handleOut.isZero()||!this._segment2._handleIn.isZero()},hasLength:function(e){return(!this.getPoint1().equals(this.getPoint2())||this.hasHandles())&&this.getLength()>(e||0)},isCollinear:function(e){return e&&this.isStraight()&&e.isStraight()&&this.getLine().isCollinear(e.getLine())},isHorizontal:function(){return this.isStraight()&&1e-8>_(this.getTangentAtTime(.5).y)},isVertical:function(){return this.isStraight()&&1e-8>_(this.getTangentAtTime(.5).x)}}),{beans:!1,getLocationAt:function(e,t){return this.getLocationAtTime(t?e:this.getTimeAt(e))},getLocationAtTime:function(e){return null!=e&&0<=e&&1>=e?new J(this,e):null},getTimeAt:function(e,t){return Z.getTimeAt(this.getValues(),e,t)},getParameterAt:"#getTimeAt",getOffsetAtTime:function(e){return this.getPartLength(0,e)},getLocationOf:function(){return this.getLocationAtTime(this.getTimeOf(B.read(arguments)))},getOffsetOf:function(){var e=this.getLocationOf.apply(this,arguments);return e?e.getOffset():null},getTimeOf:function(){return Z.getTimeOf(this.getValues(),B.read(arguments))},getParameterOf:"#getTimeOf",getNearestLocation:function(){var e=B.read(arguments),n=this.getValues(),a=Z.getNearestTime(n,e),t=Z.getPoint(n,a);return new J(this,a,t,null,e.getDistance(t))},getNearestPoint:function(){var e=this.getNearestLocation.apply(this,arguments);return e?e.getPoint():e}},new function(){var e=["getPoint","getTangent","getNormal","getWeightedTangent","getWeightedNormal","getCurvature"];return S.each(e,function(e){this[e+"At"]=function(t,n){var a=this.getValues();return Z[e](a,n?t:Z.getTimeAt(a,t))},this[e+"AtTime"]=function(t){return Z[e](this.getValues(),t)}},{statics:{_evaluateMethods:e}})},new function(){function e(e){var n=e[0],a=e[1],i=e[2],r=e[3],o=e[4],s=e[5],d=e[6],l=e[7];return function(e){var t=((9*(i-o)+3*(d-n))*e+(6*(n+o)-12*i))*e+3*(i-n),c=((9*(r-s)+3*(l-a))*e+(6*(a+s)-12*r))*e+3*(r-a);return u(t*t+c*c)}}function n(e,t){return w(2,d(16,x(32*_(t-e))))}function a(e,n,t,a){if(null==n||0>n||1T?(C=3*(p-c),k=3*(m-h)):(C=(3*v*n+2*w)*n+f,k=(3*E*n+2*_)*n+b),a){0===C&&0===k&&(nT)&&(C=c-s,k=h-l);var N=u(C*C+k*k);N&&(C/=N,k/=N)}if(3===t){var c=6*v*n+2*w,h=6*E*n+2*_,P=r(C*C+k*k,3/2);C=0===P?0:(C*h-k*c)/P,k=0}}return 2===t?new B(k,-C):new B(C,k)}return{statics:{classify:function(e){function t(e,t,n){var a=void 0!==t,i=a&&0t,r=a&&0n;return!a||(i||r)&&("loop"!==e||i&&r)||(e="arch",i=r=!1),{type:e,roots:i||r?i&&r?tr&&(s=Z.subdivide(s,r)[0],i/=r),0i?1:0),0===i)return r;var s=_,d=1e-12,l=0d)return null;var m=0;return L.findRoot(o,u,r+i/h,c,a,32,1e-12)},getPoint:function(e,n){return a(e,n,0,!1)},getTangent:function(e,n){return a(e,n,1,!0)},getWeightedTangent:function(e,n){return a(e,n,1,!1)},getNormal:function(e,n){return a(e,n,2,!0)},getWeightedNormal:function(e,n){return a(e,n,2,!1)},getCurvature:function(e,n){return a(e,n,3,!1).x},getPeaks:function(e){var t=e[0],n=e[1],a=e[2],i=e[3],r=e[4],o=e[5],s=e[6],d=e[7],l=-t+3*a-3*r+s,c=3*t-6*a+3*r,u=-3*t+3*a,h=-n+3*i-3*o+d,p=3*n-6*i+3*o,m=-3*n+3*i,g=1e-8,f=[];return L.solveCubic(9*(l*l+h*h),9*(l*c+p*h),2*(c*c+p*p)+3*(u*l+m*h),u*c+p*m,f,g,1-g),f.sort()}}}},new function(){function e(e,t,n,a,i,r,o){var s=!o&&n.getPrevious()===i,d=!o&&n!==i&&n.getNext()===i,l=1e-8,c=1-l;if(null!==a&&a>=(s?l:0)&&a<=(d?c:1)&&null!==r&&r>=(d?l:0)&&r<=(s?c:1)){var u=new J(n,a,null,o),h=new J(i,r,null,o);u._intersection=h,h._intersection=u,(!t||t(u))&&J.insert(e,u,!0)}}function n(r,o,s,l,c,h,p,m,g,f,y,v,b){if(4096<=++g||40<=++m)return g;var x=1e-9,_=o[0],E=o[1],C=o[6],k=o[7],S=j.getSignedDistance,T=S(_,E,C,k,o[2],o[3]),N=S(_,E,C,k,o[4],o[5]),P=0=x?n(o,r,l,s,c,h,!p,m,g,v,b,q,W):n(r,o,s,l,c,h,p,m,g,q,W,v,b);else if(W-q>b-v){var X=Z.subdivide(r,.5),U=(q+W)/2;g=n(o,X[0],l,s,c,h,!p,m,g,v,b,q,U),g=n(o,X[1],l,s,c,h,!p,m,g,v,b,U,W)}else{var X=Z.subdivide(o,.5),G=(v+b)/2;g=n(X[0],r,l,s,c,h,!p,m,g,v,G,q,W),g=n(X[1],r,l,s,c,h,!p,m,g,G,b,q,W)}return g}function a(e,t,n,a){var i=[0,e],r=[1/3,t],o=[2/3,n],s=[1,a],d=t-(2*e+a)/3,l=n-(e+2*a)/3,c;if(0>d*l)c=[[i,r,s],[i,o,s]];else{var u=d/l;c=[2<=u?[i,r,s]:.5>=u?[i,o,s]:[i,r,o,s],[i,s]]}return 0>(d||l)?c.reverse():c}function i(e,n,a,i){return e[0][1]i?t(n,!1,i):e[0][0]}function t(e,t,n){for(var a=e[0][0],r=e[0][1],o=1,s=e.length;o=n:l<=n)return l===n?d:a+(n-r)*(d-a)/(l-r);a=d,r=l}return null}function r(e,n,a,r,o){var d=L.isZero;if(d(r)&&d(o)){var l=Z.getTimeOf(e,new B(n,a));return null===l?[]:[l]}for(var t=h(-o,r),c=s(t),u=g(t),p=[],m=[],f=0;8>f;f+=2){var w=e[f]-n,v=e[f+1]-a;p.push(w*u-v*c,w*c+v*u)}return Z.solveCubic(p,1,0,m,0,1),m}function o(t,n,a,o,s,d,c){for(var u=n[0],h=n[1],p=n[6],m=n[7],g=r(t,u,h,p-u,m-h),f=0,w=g.length;fp(a[0],a[2],a[4],a[6])&&p(t[0],t[2],t[4],t[6])-hp(a[1],a[3],a[5],a[7])&&p(t[1],t[3],t[5],t[7])-hy;y++)v=f[y],e(c,u,r,v[0],s,v[1],!0);else{var b=Z.isStraight(t),x=Z.isStraight(a),_=b&&x,E=b&&!x,C=c.length;if((_?l:b||x?o:n)(E?a:t,E?t:a,E?s:r,E?r:s,c,u,E,0,0,0,1,0,1),!_||c.length===C)for(var y=0;4>y;y++){var k=y>>1,S=1&y,T=6*k,N=6*S,P=new B(t[T],t[T+1]),L=new B(a[N],a[N+1]);P.isClose(L,h)&&e(c,u,r,k,s,S)}}}return c}function u(t,n,a,i){var r=Z.classify(t);if("loop"===r.type){var o=r.roots;e(a,i,n,o[0],n,o[1])}return a}function p(e,t,n,a,r,o){var s=!t;s&&(t=e);for(var d=e.length,h=t.length,p=[],m=[],g=0,f,w;gb&&2>v.length;b++){var x=1&b,E=1^x,C=b>>1,k=Z.getTimeOf(y[x],new B(y[E][C?6:0],y[E][C?7:1]));if(null!=k){var S=x?[C,k]:[k,C];(!v.length||a(S[0]-v[0][0])>o&&a(S[1]-v[0][1])>o)&&v.push(S)}if(2s||a(N[3]-T[3])>s||a(N[4]-T[4])>s||a(N[5]-T[5])>s)&&(v=null)}return v}return{getIntersections:function(e){var t=this.getValues(),n=e&&e!==this&&e.getValues();return n?c(t,n,this,e,[]):u(t,this,[])},statics:{getOverlaps:m,getIntersections:p,getCurveLineIntersections:r}}}),J=S.extend({_class:"CurveLocation",initialize:function(e,t,n,a,i){if(.99999999<=t){var r=e.getNext();r&&(t=0,e=r)}this._setCurve(e),this._time=t,this._point=n||e.getPointAtTime(t),this._overlap=a,this._distance=i,this._intersection=this._next=this._previous=null},_setCurve:function(e){var t=e._path;this._path=t,this._version=t?t._version:0,this._curve=e,this._segment=null,this._segment1=e._segment1,this._segment2=e._segment2},_setSegment:function(e){this._setCurve(e.getCurve()),this._segment=e,this._time=e===this._segment1?0:1,this._point=e._point.clone()},getSegment:function(){var e=this._segment;if(!e){var t=this.getCurve(),n=this.getTime();0===n?e=t._segment1:1===n?e=t._segment2:null!=n&&(e=t.getPartLength(0,n)t&&et||e=r&&a<=o,l=i>=r&&i<=o;if(s&&l)return!this.isTouching();var c=this.getCurve(),u=ao&&(c=c.getNext()),i>o&&(h=h.getNext()),!u||!c||!p||!h)return!1;var m=[];s||(e(u,!0),e(c,!1)),l||(e(p,!0),e(h,!1));var g=this.getPoint(),f=d.apply(Math,m),w=s?c.getTangentAtTime(a):c.getPointAt(f).subtract(g),y=s?w.negate():u.getPointAt(-f).subtract(g),v=l?h.getTangentAtTime(i):h.getPointAt(f).subtract(g),b=l?v.negate():p.getPointAt(-f).subtract(g),x=y.getAngle(),_=w.getAngle(),E=b.getAngle(),C=v.getAngle();return s?!!(t(x,E,C)^t(_,E,C)&&t(x,C,E)^t(_,C,E)):!!(t(E,x,_)^t(C,x,_)&&t(E,_,x)^t(C,_,x))},hasOverlap:function(){return!!this._overlap}},S.each(Z._evaluateMethods,function(e){this[e]=function(){var t=this.getCurve(),n=this.getTime();return null!=n&&t&&t[e+"At"](n,!0)}},{preserve:!0}),new function(){function e(e,t,n){function a(n,a){for(var r=n+a,s;-1<=r&&r<=o&&(s=e[(r%o+o)%o],!!t.getPoint().isClose(s.getPoint(),1e-7));r+=a)if(t.equals(s))return s;return null}for(var o=e.length,i=0,s=o-1;i<=s;){var d=i+s>>>1,c=e[d],u;if(n&&(u=t.equals(c)?c:a(d,-1)||a(d,1)))return t._overlap&&(u._overlap=u._intersection._overlap=!0),u;var h=t.getPath(),p=c.getPath(),m=h===p?t.getIndex()+t.getTime()-(c.getIndex()+c.getTime()):h._id-p._id;0>m?s=d-1:i=d+1}return e.splice(i,0,t),t}return{statics:{insert:e,expand:function(t){for(var n=t.slice(),a=t.length-1;0<=a;a--)e(n,t[a]._intersection,!1);return n}}}}),$=V.extend({_class:"PathItem",_selectBounds:!1,_canScaleStroke:!0,beans:!0,initialize:function(){},statics:{create:function(e){var t,n,a;if(S.isPlainObject(e)?(n=e.segments,t=e.pathData):Array.isArray(e)?n=e:"string"==typeof e&&(t=e),n){var i=n[0];a=i&&Array.isArray(i[0])}else t&&(a=1<(t.match(/m/gi)||[]).length||/z\s*\S+/i.test(t));var r=a?te:ee;return new r(e)}},_asPathItem:function(){return this},isClockwise:function(){return 0<=this.getArea()},setClockwise:function(e){this.isClockwise()!=(e=!!e)&&this.reverse()},setPathData:function(e){function t(e,t){var n=+d[e];return r&&(n+=o[t]),n}function n(e){return new B(t(e,"x"),t(e+1,"y"))}var a=e&&e.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),r=!1,o=new B,s=new B,d,c,u;this.clear();for(var h=0,p=a&&a.length;hc&&this[a?"removeSegments":"removeChildren"](c,l);for(var h=0;h1-i&&(n++,a=0);var r=this.getCurves();if(0<=n&&n=i&&r[n++].divideAtTime(a);var o=this.removeSegments(n,this._segments.length,!0),s;return this._closed?(this.setClosed(!1),s=this):(s=new ee(V.NO_INSERT),s.insertAbove(this),s.copyAttributes(this)),s._add(o,0),this.addSegment(o[0]),s}return null},split:function(e,t){var n=void 0===t?e:(a=this.getCurves()[e])&&a.getLocationAtTime(t),a;return null==n?null:this.splitAt(n)},join:function(e,t){var n=t||0;if(e&&e!==this){var a=e._segments,i=this.getLastSegment(),r=e.getLastSegment();if(!r)return this;i&&i._point.isClose(r._point,n)&&e.reverse();var o=e.getFirstSegment();if(i&&i._point.isClose(o._point,n))i.setHandleOut(o._handleOut),this._add(a.slice(1));else{var s=this.getFirstSegment();s&&s._point.isClose(o._point,n)&&e.reverse(),r=e.getLastSegment(),s&&s._point.isClose(r._point,n)?(s.setHandleIn(r._handleIn),this._add(a.slice(0,a.length-1),0)):this._add(a.slice())}e._closed&&this._add([a[0]]),e.remove()}var d=this.getFirstSegment(),l=this.getLastSegment();return d!==l&&d._point.isClose(l._point,n)&&(d.setHandleIn(l._handleIn),l.remove(),this.setClosed(!0)),this},reduce:function(e){for(var t=this.getCurves(),n=e&&e.simplify,a=n?1e-7:0,r=t.length-1,o;0<=r;r--)o=t[r],!o.hasHandles()&&(!o.hasLength(a)||n&&o.isCollinear(o.getNext()))&&o.remove();return this},reverse:function(){this._segments.reverse();for(var e=0,t=this._segments.length;en&&h?n%c:0>n?n+c:n,c-1)}var r=this,o=e||{},s=o.type||"asymmetric",l=this._segments,c=l.length,h=this._closed,p=h&&void 0===o.from&&void 0===o.to,g=t(o.from,0),w=t(o.to,c-1);if(g>w)if(h)g-=c;else{var _=g;g=w,w=_}if(/^(?:asymmetric|continuous)$/.test(s)){var E="asymmetric"===s,C=d,k=w-g+1,S=k-1,T=p?C(k,4):1,N=T,P=T,L=[];if(h||(N=C(1,g),P=C(1,c-w-1)),S+=N+P,1>=S)return;for(var I=0,z=g-N;I<=S;I++,z++)L[I]=l[(0>z?z+c:z)%c]._point;for(var B=L[0]._x+2*L[1]._x,A=L[0]._y+2*L[1]._y,M=2,D=S-1,O=[B],R=[A],F=[M],V=[],q=[],I=1;Iz?z+c:z],X=G._point,H=V[I]-X._x,K=q[I]-X._y;(p||IN)&&G.setHandleIn(-H,-K)}}else for(var I=g;I<=w;I++)l[0>I?I+c:I].smooth(o,!p&&I===g,!p&&I===w)},toShape:function(e){function t(e,t){var n=r[e],a=n.getNext(),i=r[t],o=i.getNext();return n._handleOut.isZero()&&a._handleIn.isZero()&&i._handleOut.isZero()&&o._handleIn.isZero()&&a._point.subtract(n._point).isCollinear(o._point.subtract(i._point))}function n(e){var t=r[e],n=t.getNext(),a=t._handleOut,i=n._handleIn,o=.5522847498307936;if(a.isOrthogonal(i)){var s=t._point,d=n._point,l=new j(s,a,!0).intersect(new j(d,i,!0),!0);return l&&L.isZero(a.getLength()/l.subtract(s).getLength()-o)&&L.isZero(i.getLength()/l.subtract(d).getLength()-o)}return!1}function a(e,t){return r[e]._point.getDistance(r[t]._point)}if(!this._closed)return null;var r=this._segments,i,o,s,d;if(!this.hasHandles()&&4===r.length&&t(0,2)&&t(1,3)&&function(e){var t=r[e],n=t.getPrevious(),a=t.getNext();return n._handleOut.isZero()&&t._handleIn.isZero()&&t._handleOut.isZero()&&a._handleIn.isZero()&&t._point.subtract(n._point).isOrthogonal(a._point.subtract(t._point))}(1)?(i=U.Rectangle,o=new A(a(0,3),a(0,1)),d=r[1]._point.add(r[2]._point).divide(2)):8===r.length&&n(0)&&n(2)&&n(4)&&n(6)&&t(1,5)&&t(3,7)?(i=U.Rectangle,o=new A(a(1,6),a(0,3)),s=o.subtract(new A(a(0,7),a(1,2))).divide(2),d=r[3]._point.add(r[4]._point).divide(2)):4===r.length&&n(0)&&n(1)&&n(2)&&n(3)&&(L.isZero(a(0,2)-a(1,3))?(i=U.Circle,s=a(0,2)/2):(i=U.Ellipse,s=new A(a(2,0)/2,a(3,1)/2)),d=r[1]._point),i){var l=this.getPosition(!0),c=new i({center:l,size:o,radius:s,insert:!1});return c.copyAttributes(this,!0),c._matrix.prepend(this._matrix),c.rotate(d.subtract(l).getAngle()+90),(void 0===e||e)&&c.insertAbove(this),c}return null},toPath:"#clone",compare:function e(t){if(!t||t instanceof te)return e.base.call(this,t);var n=this.getCurves(),a=t.getCurves(),r=n.length,o=a.length;if(!r||!o)return r==o;for(var s=n[0].getValues(),d=[],l=0,c=0,u=0,h,p,m;u=o&&(h=0),m=d[h]||a[h].getValues(),p=0),!s)return y[0]===h&&y[1]===p;continue}}}break}return!1},_hitTestSelf:function(e,t,n,a){function r(t,n){return 1>=e.subtract(t).divide(n).length}function o(e,n,a){if(!t.selected||n.isSelected()){var i=e._point;if(n!==i&&(n=n.add(i)),r(n,f))return new K(a,c,{segment:e,point:n})}}function s(e,n){return(n||t.segments)&&o(e,e._point,"segment")||!n&&t.handles&&(o(e,e._handleIn,"handle-in")||o(e,e._handleOut,"handle-out"))}function d(e){C.add(e)}function l(t){var n=m||0e)return s.getLocationAt(e-o)}if(0=S.remain(arguments))h=o,o=B.read(arguments);else{var b=A.read(arguments),E=L.isZero;if(E(b.width)||E(b.height))return this.lineTo(o);var C=S.read(arguments),c=!!S.read(arguments),k=!!S.read(arguments),v=r.add(o).divide(2),T=r.subtract(v).rotate(-C),N=T.x,P=T.y,y=t(b.width),I=t(b.height),M=y*y,D=I*I,O=N*N,F=P*P,V=n(O/M+F/D);if(1t(V)&&(V=0),0>V)throw new Error("Cannot create an arc with the given arguments");p=new B(y*P/I,-I*N/y).multiply((k===c?-1:1)*n(V)).rotate(C).add(v),w=new R().translate(p).rotate(C).scale(y,I),f=w._inverseTransform(r),m=f.getDirectedAngle(w._inverseTransform(o)),!c&&0m&&(m+=360)}if(h){var q=new j(r.add(h).divide(2),h.subtract(r).rotate(90),!0),W=new j(h.add(o).divide(2),o.subtract(h).rotate(90),!0),U=new j(r,o),G=U.getSide(h);if(p=q.intersect(W,!0),!p){if(!G)return this.lineTo(o);throw new Error("Cannot create an arc with the given arguments")}f=r.subtract(p),m=f.getDirectedAngle(o.subtract(p));var X=U.getSide(p);0===X?m=G*t(m):G===X&&(m+=0>m?360:-360)}for(var H=t(m),K=360<=H?4:x((H-1e-7)/90),Y=m/K,Z=Y*l/360,J=4/3*s(Z)/(1+g(Z)),z=[],$=0;$<=K;$++){var T=o,ee=null;if($t;t++)Z._addBounds(u[t],u[t+4],c[t+2],c[t],t,o?o[t]:0,h,p,m);var n=u;u=c,c=n}var d=e[0];if(!d)return new D;for(var c=[,,,,,,],u=d._transformCoordinates(a,[,,,,,,]),h=u.slice(0,2),p=h.slice(),m=[,,],g=1,f=e.length;gu.getDirectedAngle(h)&&(u=u.negate(),h=h.negate()),s&&o(c),o(c.add(u)),"miter"===t){var p=new j(c.add(u),new B(-u.y,u.x),!0).intersect(new j(c.add(h),new B(-h.y,h.x),!0),!0);p&&c.getDistance(p)<=a*n&&o(p)}o(c.add(h))},_addSquareCap:function(e,t,n,a,i,r,o){var s=e._point.transform(a),d=e.getLocation(),l=d.getNormal().multiply(0===d.getTime()?n:-n).transform(i);"square"===t&&(o&&(r(s.subtract(l)),r(s.add(l))),s=s.add(l.rotate(-90))),r(s.add(l)),r(s.subtract(l))},getHandleBounds:function(e,t,n,a,r){var o=n.getStyle(),s=r.stroke&&o.hasStroke(),d,c;if(s){var u=n._getStrokeMatrix(a,r),h=o.getStrokeWidth()/2,p=h;"miter"===o.getStrokeJoin()&&(p=h*o.getMiterLimit()),"square"===o.getStrokeCap()&&(p=w(p,h*Math.SQRT2)),d=ee._getStrokePadding(h,u),c=ee._getStrokePadding(p,u)}for(var m=[,,,,,,],g=1/0,f=-g,v=g,b=f,_=0,E=e.length,l;_C;C+=2){var k=C?d:c,S=k?k[0]:0,T=k?k[1]:0,N=m[C],x=m[C+1],y=N-S,P=N+S,L=x-T,I=x+T;yf&&(f=P),Lb&&(b=I)}}return new D(g,v,f-g,b-v)}}});ee.inject({statics:new function(){function e(e,t,n){var a=S.getNamed(n),i=new ee(a&&!1==a.insert&&V.NO_INSERT);return i._add(e),i._closed=t,i.set(a,{insert:!0})}function t(t,n,r){for(var o=[,,,,],s=0,d;4>s;s++)d=a[s],o[s]=new Q(d._point.multiply(n).add(t),d._handleIn.multiply(n),d._handleOut.multiply(n));return e(o,!0,r)}var n=.5522847498307936,a=[new Q([-1,0],[0,n],[0,-n]),new Q([0,-1],[-n,0],[n,0]),new Q([1,0],[0,-n],[0,n]),new Q([0,1],[n,0],[-n,0])];return{Line:function(){return e([new Q(B.readNamed(arguments,"from")),new Q(B.readNamed(arguments,"to"))],!1,arguments)},Circle:function(){var e=B.readNamed(arguments,"center"),n=S.readNamed(arguments,"radius");return t(e,new A(n),arguments)},Rectangle:function(){var t=D.readNamed(arguments,"rectangle"),a=A.readNamed(arguments,"radius",0,{readNull:!0}),i=t.getBottomLeft(!0),r=t.getTopLeft(!0),o=t.getTopRight(!0),s=t.getBottomRight(!0),d;if(!a||a.isZero())d=[new Q(i),new Q(r),new Q(o),new Q(s)];else{a=A.min(a,t.getSize(!0).divide(2));var l=a.width,c=a.height,u=l*n,h=c*n;d=[new Q(i.add(l,0),null,[-u,0]),new Q(i.subtract(0,c),[0,h]),new Q(r.add(0,c),null,[0,-h]),new Q(r.add(l,0),[-u,0],null),new Q(o.subtract(l,0),null,[u,0]),new Q(o.add(0,c),[0,-h],null),new Q(s.subtract(0,c),null,[0,h]),new Q(s.subtract(l,0),[u,0])]}return e(d,!0,arguments)},RoundRectangle:"#Rectangle",Ellipse:function(){var e=U._readEllipse(arguments);return t(e.center,e.radius,arguments)},Oval:"#Ellipse",Arc:function(){var e=B.readNamed(arguments,"from"),t=B.readNamed(arguments,"through"),n=B.readNamed(arguments,"to"),a=S.getNamed(arguments),i=new ee(a&&!1==a.insert&&V.NO_INSERT);return i.moveTo(e),i.arcTo(t,n),i.set(a)},RegularPolygon:function(){for(var t=B.readNamed(arguments,"center"),n=S.readNamed(arguments,"sides"),a=S.readNamed(arguments,"radius"),r=0==n%3,o=new B(0,r?-a:a),s=r?-1:.5,d=Array(n),l=0;l=s&&(v/=f):(c=!w.hasHandles()||h&&h[a(w)],m=[],f=null,g=w)),x){m&&m.push(y);continue}else t&&o.unshift(y);if(f=b,vd)_=w._segment2;else{var E=w.divideAtTime(v,!0);c&&u.push(w,E),_=E._segment1;for(var C=m.length-1,k;0<=C;C--)k=m[C],k._time=(k._time-v)/(1-v)}y._setSegment(_);var S=_._intersection,T=y._intersection;if(S){i(S,T);for(var N=S;N;)i(N._intersection,S),N=N._next}else _._intersection=T}return n||r(u),o||e}function l(e,n,r,o,s){function t(i){var u=i[c+0],m=i[c+6];if(!(fp(u,m))){var w=i[d+0],v=i[d+2],_=i[d+4],E=i[d+6];if(u===m)return void((wb||Eb)&&(S=!0));var T=f===u?0:f===m?1:b>p(w,v,_,E)||xm?1:-1,L=z[c]>z[c+6]?1:-1,I=z[d+6];return f===u?(a==L?w!=I&&(Ix?(k+=a,S=!0):I>b&&tx&&(k+=a),N=0):(tx?k+=a:S=!0,t>g-y&&tb&&t=h(n,a,o,s))for(var u=e[d+0],m=e[d+2],g=e[d+4],w=e[d+6],y=b>p(u,m,g,w)||xu.quality;w++){p=c*g[w];for(var y=0,v=s.length;yu.quality&&(u=T);break}p-=x}}for(var y=s.length-1;0<=y;y--)s[y].segment._winding=u}function u(e,t){function n(e){var n;return!(!e||e._visited||t&&(!t[(n=e._winding||{}).winding]||t.unite&&2===n.winding&&n.windingL&&n.windingR))}function a(e){if(e)for(var t=0,n=d.length;t=h(c,u,g,f)&&a<=p(c,u,g,f))for(var w=Z.getMonoCurves(l),y=0,v=w.length;y=b&&a<=_||a>=_&&a<=b)){var E=a===b?m[0]:a===_?m[6]:1===Z.solveCubic(m,1,a,o,0,1)?Z.getPoint(m,o[0]).x:(m[0]+m[6])/2;r.push(E)}}}1p&&!(a&&Z.isStraight(e))&&!Z.isFlatEnough(e,t||.25)){var o=Z.subdivide(e,.5),d=(i+r)/2;s(o[0],n,i,d),s(o[1],n,d,r)}else{var l=e[6]-e[0],m=e[7]-e[1],g=u(l*l+m*m);0=e){this.index=r;var s=t[r-1],d=s&&s.index===o.index?s.time:0,l=s?s.offset:0;return{index:o.index,time:d+(o.time-d)*(e-l)/(o.offset-l)}}}return{index:t[n-1].index,time:1}},drawPart:function(e,t,n){for(var a=this._get(t),r=this._get(n),o=a.index,s=r.index,d;o<=s;o++)d=Z.getPart(this.curves[o],o===a.index?a.time:0,o===r.index?r.time:1),o===a.index&&e.moveTo(d[0],d[1]),e.bezierCurveTo.apply(e,d.slice(2))}},S.each(Z._evaluateMethods,function(e){this[e+"At"]=function(t){var n=this._get(t);return Z[e](this.curves[n.index],n.time)}},{})),ae=S.extend({initialize:function(e){for(var t=this.points=[],n=e._segments,a=e._closed,r=0,o=n.length,s,d;r=m;m++){var f=this.generateBezier(n,a,u,r,o),y=this.findMaxError(n,a,f,u);if(y.error=h)break;p=this.reparameterize(n,a,u,f),h=y.error}var v=s[g-1].subtract(s[g+1]);this.fitCubic(e,t,n,g,r,v),this.fitCubic(e,t,g,a,v.negate(),o)},addCurve:function(e,t){var n=e[e.length-1];n.setHandleOut(t[1].subtract(t[0])),e.push(new Q(t[3],t[2].subtract(t[3])))},generateBezier:function(e,n,a,r,o){for(var s=1e-12,d=_,l=this.points,c=l[e],h=l[n],p=[[0,0],[0,0]],m=[0,0],g=0;gs){var S=p[0][0]*m[1]-p[1][0]*m[0],T=m[0]*p[1][1]-m[1]*p[0][1];C=T/E,k=S/E}else{var N=p[0][0]+p[0][1],P=p[1][0]+p[1][1];C=k=d(N)>s?m[0]/N:d(P)>s?m[1]/P:0}var L=h.getDistance(c),I=s*L,z,B;if(CL*L&&(C=k=L/3,z=B=null)}return[c,c.add(z||r.normalize(C)),h.add(B||o.normalize(k)),h]},reparameterize:function(e,t,n,a){for(var r=e;r<=t;r++)n[r-e]=this.findRoot(a,this.points[r],n[r-e]);for(var r=1,o=n.length;r=o;o++)a[o]=e[o+1].subtract(e[o]).multiply(3);for(var o=0;1>=o;o++)r[o]=a[o+1].subtract(a[o]).multiply(2);var s=this.evaluate(3,e,n),d=this.evaluate(2,a,n),l=this.evaluate(1,r,n),c=s.subtract(t),u=d.dot(d)+c.dot(l);return L.isZero(u)?n:n-c.dot(d)/u},evaluate:function(e,n,a){for(var t=n.slice(),r=1;r<=e;r++)for(var o=0;o<=e-r;o++)t[o]=t[o].multiply(1-a).add(t[o+1].multiply(a));return t[0]},chordLengthParameterize:function(e,t){for(var n=[0],a=e+1;a<=t;a++)n[a-e]=n[a-e-1]+this.points[a].getDistance(this.points[a-1]);for(var a=1,r=t-e;a<=r;a++)n[a]/=n[r];return n},findMaxError:function(e,t,a,r){for(var o=n((t-e+1)/2),s=0,d=e+1;d=s&&(s=u,o=d)}return{error:s,index:o}}}),ie=V.extend({_class:"TextItem",_applyMatrix:!1,_canApplyMatrix:!1,_serializeFields:{content:null},_boundsOptions:{stroke:!1,handle:!1},initialize:function(e){this._content="",this._lines=[];var t=e&&S.isPlainObject(e)&&void 0===e.x&&void 0===e.y;this._initialize(t&&e,!t&&B.read(arguments))},_equals:function(e){return this._content===e._content},copyContent:function(e){this.setContent(e._content)},getContent:function(){return this._content},setContent:function(e){this._content=""+e,this._lines=this._content.split(/\r\n|\n|\r/mg),this._changed(265)},isEmpty:function(){return!this._content},getCharacterStyle:"#getStyle",setCharacterStyle:"#setStyle",getParagraphStyle:"#getStyle",setParagraphStyle:"#setStyle"}),re=ie.extend({_class:"PointText",initialize:function(){ie.apply(this,arguments)},getPoint:function(){var e=this._matrix.getTranslation();return new z(e.x,e.y,this,"setPoint")},setPoint:function(){var e=B.read(arguments);this.translate(e.subtract(this._matrix.getTranslation()))},_draw:function(e,t,n){if(this._content){this._setStyles(e,t,n);var a=this._lines,r=this._style,o=r.hasFill(),s=r.hasStroke(),d=r.getLeading(),c=e.shadowColor;e.font=r.getFontStyle(),e.textAlign=r.getJustification();for(var u=0,h=a.length;ua;a++)r=t[a+1],n[a]=parseInt(1==r.length?r+r:r,16)/255}else if(t=e.match(/^rgba?\((.*)\)$/)){n=t[1].split(",");for(var a=0,o=n.length,r;aa?r/255:r}else if(E){var s=i[e];if(!s){l||(l=_e.getContext(1,1),l.globalCompositeOperation="copy"),l.fillStyle="rgba(0,0,0,0)",l.fillStyle=e,l.fillRect(0,0,1,1);var d=l.getImageData(0,0,1,1).data;s=i[e]=[d[0]/255,d[1]/255,d[2]/255]}n=s.slice()}else n=[0,0,0];return n}var t={gray:["gray"],rgb:["red","green","blue"],hsb:["hue","saturation","brightness"],hsl:["hue","saturation","lightness"],gradient:["gradient","origin","destination","highlight"]},a={},i={},r=[[0,3,1],[2,0,1],[1,0,3],[1,2,0],[3,1,0],[0,1,2]],s={"rgb-hsb":function(e,t,n){var a=w(e,t,n),i=d(e,t,n),r=a-i,o=0==r?0:60*(a==e?(t-n)/r+(tu?r/(a+i):r/(2-a-i);return[c,l,u]},"hsl-rgb":function(e,t,n){if(e=(e/360%1+1)%1,0===t)return[n,n,n];for(var a=[e+1/3,e,e-1/3],r=.5>n?n*(1+t):n+t-n*t,o=2*n-r,s=[],d=0,l;3>d;d++)l=a[d],0>l&&(l+=1),16*l?o+6*(r-o)*l:1>2*l?r:2>3*l?o+6*((r-o)*(2/3-l)):o;return s},"rgb-gray":function(e,t,n){return[.2989*e+.587*t+.114*n]},"gray-rgb":function(e){return[e,e,e]},"gray-hsb":function(e){return[0,0,e]},"gray-hsl":function(e){return[0,0,e]},"gradient-rgb":function(){return[]},"rgb-gradient":function(){return[]}},l;return S.each(t,function(e,n){a[n]=[],S.each(e,function(e,i){var r=S.capitalize(e),o=/^(hue|saturation)$/.test(e),s=a[n][i]="gradient"===e?function(e){var t=this._components[0];return e=se.read(Array.isArray(e)?e:arguments,0,{readNull:!0}),t!==e&&(t&&t._removeOwner(this),e&&e._addOwner(this)),e}:"gradient"===n?function(){return B.read(arguments,0,{readNull:"highlight"===e,clone:!0})}:function(e){return null==e||isNaN(e)?0:e};this["get"+r]=function(){return this._type===n||o&&/^hs[bl]$/.test(this._type)?this._components[i]:this._convert(n)[i]},this["set"+r]=function(e){this._type===n||o&&/^hs[bl]$/.test(this._type)||(this._components=this._convert(n),this._properties=t[n],this._type=n),this._components[i]=s.call(this,e),this._changed()}},this)},{_class:"Color",_readIndex:!0,initialize:function n(r){var o=arguments,s=this.__read,d=0,c,u,h,p;Array.isArray(r)&&(o=r,r=o[0]);var m=null!=r&&typeof r;if("string"===m&&r in t&&(c=r,r=o[1],Array.isArray(r)?(u=r,h=o[2]):(s&&(d=1),o=S.slice(o,1),m=typeof r)),!u){if(p="number"===m?o:"object"===m&&null!=r.length?r:null,p){c||(c=3<=p.length?"rgb":"gray");var g=t[c].length;h=p[g],s&&(d+=p===arguments?g+(null==h?0:1):1),p.length>g&&(p=S.slice(p,0,g))}else if("string"===m)c="rgb",u=e(r),4===u.length&&(h=u[3],u.length--);else if("object"===m)if(r.constructor===n){if(c=r._type,u=r._components.slice(),h=r._alpha,"gradient"===c)for(var f=1,w=u.length,y;fe?0:1a&&n.push(0>a?0:a),e?"#"+(16777216+(n[0]<<16)+(n[1]<<8)+n[2]).toString(16).slice(1):(4==n.length?"rgba(":"rgb(")+n.join(",")+")"},toCanvasStyle:function(e,t){if(this._canvasStyle)return this._canvasStyle;if("gradient"!==this._type)return this._canvasStyle=this.toCSS();var n=this._components,a=n[0],r=a._stops,o=n[1],s=n[2],d=n[3],c=t&&t.inverted(),u;if(c&&(o=c._transformPoint(o),s=c._transformPoint(s),d&&(d=c._transformPoint(d))),a._radial){var h=s.getDistance(o);if(d){var p=d.subtract(o);p.getLength()>h&&(d=o.add(p.normalize(h-.1)))}var m=d||o;u=e.createRadialGradient(m.x,m.y,0,o.x,o.y,h)}else u=e.createLinearGradient(o.x,o.y,s.x,s.y);for(var g=0,f=r.length;ge.length)throw new Error("Gradient stop list needs to contain at least two stops.");var t=this._stops;if(t)for(var n=0,a=t.length;ns;s++){var d=r[s],l=d?d+o:t;if(l in e){if(n)e[l]=a;else return e[l];break}}}return{getStyles:function(e){var t=e&&9!==e.nodeType?e.ownerDocument:e,n=t&&t.defaultView;return n&&n.getComputedStyle(e,"")},getBounds:function(e,t){var n=e.ownerDocument,a=n.body,i=n.documentElement,r;try{r=e.getBoundingClientRect()}catch(t){r={left:0,top:0,width:0,height:0}}var o=r.left-(i.clientLeft||a.clientLeft||0),s=r.top-(i.clientTop||a.clientTop||0);if(!t){var d=n.defaultView;o+=d.pageXOffset||i.scrollLeft||a.scrollLeft,s+=d.pageYOffset||i.scrollTop||a.scrollTop}return new D(o,s,r.width,r.height)},getViewportBounds:function(e){var t=e.ownerDocument,n=t.defaultView,a=t.documentElement;return new D(0,0,n.innerWidth||a.clientWidth,n.innerHeight||a.clientHeight)},getOffset:function(e,t){return ce.getBounds(e,t).getPoint()},getSize:function(e){return ce.getBounds(e,!0).getSize()},isInvisible:function(e){return ce.getSize(e).equals(new A(0,0))},isInView:function(e){return!ce.isInvisible(e)&&ce.getViewportBounds(e).intersects(ce.getBounds(e,!0))},isInserted:function(e){return C.body.contains(e)},getPrefixed:function(t,n){return t&&e(t,n)},setPrefixed:function(t,n,a){if("object"==typeof n)for(var i in n)e(t,i,!0,n[i]);else e(t,n,!0,a)}}},ue={add:function(e,t){if(e)for(var n in t)for(var a=t[n],r=n.split(/[\s,]+/g),o=0,s=r.length;or?-1:1):r,n(t,e,t.viewToProject(i))}},scroll:t};p[c]=function(t){var n=he._focused=e(t);r||(r=!0,n._handleMouseEvent("mousedown",t))},m[u]=function(a){var i=he._focused;if(!o){var r=e(a);r?i!==r&&(i&&n(i,a),!d&&(d=i),i=he._focused=l=r):l&&l===i&&(d&&!d.isInserted()&&(d=null),i=he._focused=d,d=null,t())}i&&n(i,a)},m[c]=function(){o=!0},m[h]=function(e){var t=he._focused;t&&r&&t._handleMouseEvent("mouseup",e),o=r=!1},ue.add(C,m),ue.add(E,{load:t});var g=!1,w=!1,y={doubleclick:"click",mousedrag:"mousemove"},v=!1,b={mousedown:{mousedown:1,mousedrag:1,click:1,doubleclick:1},mouseup:{mouseup:1,mousedrag:1,click:1,doubleclick:1},mousemove:{mousedrag:1,mousemove:1,mouseenter:1,mouseleave:1}},x,k,S,T,N,P,L,I,z;return{_viewEvents:p,_handleMouseEvent:function(e,t,n){function o(e){return s.virtual[e]||u.responds(e)||c&&c.responds(e)}var s=this._itemEvents,d=s.native[e],l="mousemove"===e,c=this._scope.tool,u=this;l&&r&&o("mousedrag")&&(e="mousedrag"),n||(n=this.getEventPoint(t));var h=this.getBounds().contains(n),p=d&&h&&u._project.hitTest(n,{tolerance:0,fill:!0,stroke:!0}),m=p&&p.item||null,f=!1,y={};if(y[e.substr(5)]=!0,d&&m!==N&&(N&&a(N,null,"mouseleave",t,n),m&&a(m,null,"mouseenter",t,n),N=m),v^h&&(a(this,null,h?"mouseenter":"mouseleave",t,n),x=h?this:null,f=!0),(h||y.drag)&&!n.equals(S)&&(i(this,m,l?e:"mousemove",t,n,S),f=!0),v=h,y.down&&h||y.up&&k){if(i(this,m,e,t,n,k),y.down){if(z=m===L&&300>Date.now()-I,T=L=m,!w&&m){for(var b=m;b&&!b.responds("mousedrag");)b=b._parent;b&&(P=m)}k=n}else y.up&&(w||m!==T||(I=Date.now(),i(this,m,z?"doubleclick":"click",t,n,k),z=!1),T=P=null);v=!1,f=!0}S=n,f&&c&&(g=c._handleMouseEvent(e,t,n,y)||g),(g&&!y.move||y.down&&o("mouseup"))&&t.preventDefault()},_handleKeyEvent:function(e,t,n,a){function i(i){i.responds(e)&&(f=r,i.emit(e,s=s||new fe(e,t,n,a)))}var r=this._scope,o=r.tool,s;this.isVisible()&&(i(this),o&&o.responds(e)&&i(o))},_countItemEvent:function(e,t){var n=this._itemEvents,a=n.native,i=n.virtual;for(var r in b)a[r]=(a[r]||0)+(b[r][e]||0)*t;i[e]=(i[e]||0)+t},statics:{updateFocus:t}}}}),pe=he.extend({_class:"CanvasView",initialize:function(e,t){if(!(t instanceof E.HTMLCanvasElement)){var n=A.read(arguments,1);if(n.isZero())throw new Error("Cannot create CanvasView with the provided argument: "+S.slice(arguments,1));t=_e.getCanvas(n)}var a=this._context=t.getContext("2d");if(a.save(),this._pixelRatio=1,!/^off|false$/.test(T.getAttribute(t,"hidpi"))){var i=E.devicePixelRatio||1,r=ce.getPrefixed(a,"backingStorePixelRatio")||1;this._pixelRatio=i/r}he.call(this,e,t),this._needsUpdate=!0},remove:function e(){return this._context.restore(),e.base.call(this)},_setElementSize:function e(t,n){var a=this._pixelRatio;if(e.base.call(this,t*a,n*a),1!==a){var i=this._element,r=this._context;if(!T.hasAttribute(i,"resize")){var o=i.style;o.width=t+"px",o.height=n+"px"}r.restore(),r.save(),r.scale(a,a)}},getPixelSize:function e(t){var n=f.agent,a;if(n&&n.firefox)a=e.base.call(this,t);else{var i=this._context,r=i.font;i.font=t+" serif",a=parseFloat(i.font),i.font=r}return a},getTextWidth:function(e,t){var n=this._context,a=n.font,r=0;n.font=e;for(var o=0,s=t.length;othis._maxDistance&&(this._maxDistance=e)},getMaxDistance:function(){return this._maxDistance},setMaxDistance:function(e){this._maxDistance=e,null!=this._minDistance&&null!=e&&ed){var u=r-d;x=r+(x-r)*r/u,E=r+(E-r)*r/u,C=r+(C-r)*r/u}if(255r[d]?(r[l]=(r[l]-r[d])*a/(r[s]-r[d]),r[s]=a):r[l]=r[s]=0,r[d]=0,x=r[0],E=r[1],C=r[2]}var i=d,o=w,r=_,s={multiply:function(){x=g*u/255,E=f*h/255,C=y*p/255},screen:function(){x=g+u-g*u/255,E=f+h-f*h/255,C=y+p-y*p/255},overlay:function(){x=128>g?2*g*u/255:255-2*(255-g)*(255-u)/255,E=128>f?2*f*h/255:255-2*(255-f)*(255-h)/255,C=128>y?2*y*p/255:255-2*(255-y)*(255-p)/255},"soft-light":function(){var e=u*g/255;x=e+g*(255-(255-g)*(255-u)/255-e)/255,e=h*f/255,E=e+f*(255-(255-f)*(255-h)/255-e)/255,e=p*y/255,C=e+y*(255-(255-y)*(255-p)/255-e)/255},"hard-light":function(){x=128>u?2*u*g/255:255-2*(255-u)*(255-g)/255,E=128>h?2*h*f/255:255-2*(255-h)*(255-f)/255,C=128>p?2*p*y/255:255-2*(255-p)*(255-y)/255},"color-dodge":function(){x=0===g?0:255===u?255:i(255,255*g/(255-u)),E=0===f?0:255===h?255:i(255,255*f/(255-h)),C=0===y?0:255===p?255:i(255,255*y/(255-p))},"color-burn":function(){x=255===g?255:0===u?0:o(0,255-255*(255-g)/u),E=255===f?255:0===h?0:o(0,255-255*(255-f)/h),C=255===y?255:0===p?0:o(0,255-255*(255-y)/p)},darken:function(){x=gu?g:u,E=f>h?f:h,C=y>p?y:p},difference:function(){x=g-u,0>x&&(x=-x),E=f-h,0>E&&(E=-E),C=y-p,0>C&&(C=-C)},exclusion:function(){x=g+u*(255-g-g)/255,E=f+h*(255-f-f)/255,C=y+p*(255-y-y)/255},hue:function(){a(u,h,p,n(g,f,y)),t(x,E,C,e(g,f,y))},saturation:function(){a(g,f,y,n(u,h,p)),t(x,E,C,e(g,f,y))},luminosity:function(){t(g,f,y,e(u,h,p))},color:function(){t(u,h,p,e(g,f,y))},add:function(){x=i(g+u,255),E=i(f+h,255),C=i(y+p,255)},subtract:function(){x=o(g-u,0),E=o(f-h,0),C=o(y-p,0)},average:function(){x=(g+u)/2,E=(f+h)/2,C=(y+p)/2},negation:function(){x=255-r(255-u-g),E=255-r(255-h-f),C=255-r(255-p-y)}},c=this.nativeModes=S.each(["source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","lighter","darker","copy","xor"],function(e){this[e]=!0},{}),l=_e.getContext(1,1),u,h,p,m,g,f,y,v,x,E,C;l&&(S.each(s,function(e,t){var n="darken"===t,a=!1;l.save();try{l.fillStyle=n?"#300":"#a00",l.fillRect(0,0,1,1),l.globalCompositeOperation=t,l.globalCompositeOperation===t&&(l.fillStyle=n?"#a00":"#300",l.fillRect(0,0,1,1),a=l.getImageData(0,0,1,1).data[0]===n?51:170)}catch(t){}l.restore(),c[t]=a}),_e.release(l)),this.process=function(e,t,n,a,r){var o=t.canvas,d="normal"===e;if(d||c[e])n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=a,d||(n.globalCompositeOperation=e),n.drawImage(o,r.x,r.y),n.restore();else{var w=s[e];if(!w)return;for(var b=n.getImageData(r.x,r.y,o.width,o.height),_=b.data,k=t.getImageData(0,0,o.width,o.height).data,S=0,T=_.length;Sw&&(s["stop-opacity"]=w),t.appendChild(Ce.create("stop",s,f))}u(e,t,"color")}return"url(#"+t.id+")"}function d(t){var n=Ce.create("text",e(t._matrix,!0),f);return n.textContent=t._content,n}function l(e,t,n){var a={},i=!n&&e.getParent(),r=[];return null!=e._name&&(a.id=e._name),S.each(ke,function(t){var n=t.get,o=t.type,d=e[n]();if(t.exportFilter?t.exportFilter(e,d):!i||!S.equals(i[n](),d)){if("color"===o&&null!=d){var l=d.getAlpha();1>l&&(a[t.attribute+"-opacity"]=l)}"style"===o?r.push(t.attribute+": "+d):a[t.attribute]=null==d?"none":"color"===o?d.gradient?s(d,e):d.toCSS(!0):"array"===o?d.join(","):"lookup"===o?t.toSVG[d]:d}}),r.length&&(a.style=r.join(";")),1===a.opacity&&delete a.opacity,e._visible||(a.visibility="hidden"),Ce.set(t,a,f)}function c(e,t){return w||(w={ids:{},svgs:{}}),e&&w.svgs[t+"-"+(e._id||e.__id||(e.__id=I.get("svg")))]}function u(e,t,n){w||c();var a=w.ids[n]=(w.ids[n]||0)+1;t.id=n+"-"+a,w.svgs[n+"-"+(e._id||e.__id)]=t}function h(e,t){var n=e,a=null;if(w){for(var r in n="svg"===e.nodeName.toLowerCase()&&e,w.svgs)a||(!n&&(n=Ce.create("svg"),n.appendChild(e)),a=n.insertBefore(Ce.create("defs"),n.firstChild)),a.appendChild(w.svgs[r]);w=null}return t.asString?new b.XMLSerializer().serializeToString(n):n}function p(e,t,n){var a=g[e._class],i=a&&a(e,t);if(i){var r=t.onExport;r&&(i=r(e,i,t)||i);var o=JSON.stringify(e._data);o&&"{}"!==o&&"null"!==o&&i.setAttribute("data-paper-data",o)}return i&&l(e,i,n)}function m(e){return e||(e={}),f=new P(e.precision),e}var g={Group:t,Layer:t,Raster:n,Path:a,Shape:i,CompoundPath:r,SymbolItem:o,PointText:d},f,w;V.inject({exportSVG:function(e){return e=m(e),h(p(this,e,!0),e)}}),F.inject({exportSVG:function(t){t=m(t);var n=this._children,a=this.getView(),r=S.pick(t.bounds,"view"),o=t.matrix||"view"===r&&a._matrix,s=o&&R.read([o]),d="view"===r?new D([0,0],a.getViewSize()):"content"===r?V._getBounds(n,s,{stroke:!0}).rect:D.read([r],0,{readNull:!0}),c={version:"1.1",xmlns:Ce.svg,"xmlns:xlink":Ce.xlink};d&&(c.width=d.width,c.height=d.height,(d.x||d.y)&&(c.viewBox=f.rectangle(d)));var u=Ce.create("svg",c,f),g=u;s&&!s.isIdentity()&&(g=u.appendChild(Ce.create("g",e(s),f)));for(var w=0,y=n.length;w\u5F00\u59CB\uFF0C\u76F4\u5230\u03A3\u4E0A\u9762\u7684\u6570\u5B57\u7ED3\u675F\uFF09\u3002"),a.createElement("div",{className:"howtocode"},a.createElement("h3",{id:"-"},"\u5982\u4F55\u5B9E\u73B0\u57FA\u672C\u65B9\u7A0B"),a.createElement("p",null,"\u6211\u4EEC\u53EF\u4EE5\u7528\u4E4B\u524D\u8BF4\u8FC7\u7684\u65B9\u7A0B\uFF0C\u6765\u7B80\u5355\u5730\u5B9E\u73B0\u57FA\u672C\u65B9\u7A0B\u4F5C\u4E3A\u6570\u5B66\u6784\u9020\uFF0C\u5982\u4E0B\uFF1A"),a.createElement("pre",null,"function Bezier(n,t):\n sum = 0\n for(k=0; k= lut.length):\n s = lut.length\n nextRow = new array(size=s+1)\n nextRow[0] = 1\n for(i=1, prev=s-1; i frames:\n step = 1.0/steps\n\n // Start off with the standard tangent/axis/normal frame\n // associated with the curve at t=0:\n frames.add(getFrenetFrame(0))\n\n // start constructing RM frames:\n for t0 = 0, t0 < 1.0, t0 += step:\n // start with the previous, known frame\n x0 = frames.last\n\n // get the next frame: we're going to keep its position and tangent,\n // but we're going to recompute the axis and normal.\n t1 = t0 + step\n x1 = { o: getPoint(t1), t: getDerivative(t) }\n\n // First we reflect x0's tangent and axis of rotation onto x1,\n // through/ the plane of reflection at the point between x0 x1\n v1 = x1.o - x0.o\n c1 = v1 \xB7 v1\n riL = x0.r - v1 * 2/c1 * v1 \xB7 x0.r\n tiL = x0.t - v1 * 2/c1 * v1 \xB7 x0.t\n\n // note that v1 is a vector, but 2/c1 and (v1 \xB7 ...) are just\n // plain numbers, so we're just scaling v1 by some constant.\n\n // Then we reflect a second time, over a plane at x1, so that\n // the frame tangent is aligned with the curve tangent again:\n v2 = x1.t - tiL\n c2 = v2 \xB7 v2\n\n // and we're done here:\n x1.r = riL - v2 * 2/c2 * v2 \xB7 riL\n x1.n = x1.r \xD7 x1.t\n frames.add(x1)\n"),a.createElement("p",null,"Ignoring comments, this is certainly more code than when we were just computing a single Frenet frame, but it's not a crazy amount more code to get much better looking normals.")),a.createElement("p",null,"Speaking of better looking, what does this actually look like? Let's revisit that earlier curve, but this time use rotation minimising frames rather than Frenet frames:"),a.createElement(i,{handler:e.props.handler,section:"pointvectors3d",title:"\xC6sthetically much better 3D curve normals",setup:e.setup,sname:"setup",draw:e.drawRMFNormals,dname:"drawRMFNormals"}),a.createElement("p",null,"Now that looks much better!"),a.createElement("p",null,"For those reading along with the code: we don't even strictly speaking need a Frenet frame to start with: we could, for instance, treat the z-axis as our initial axis of rotation, so that our initial normal is ",a.createElement("strong",null,"(0,0,1) \xD7 tangent"),", and then take things from there, but having that initial \"mathematically correct\" frame so that the initial normal seems to line up based on the curve's orientation in 3D space is quite useful."))}},components:{locale:"en-GB",title:"Component functions",getContent:function(e){return a.createElement("section",{className:"components"},a.createElement(r,{name:"components",title:"Component functions",number:"16"}),a.createElement("p",null,"One of the first things people run into when they start using B\xE9zier curves in their own programs is \"I know how to draw the curve, but how do I determine the bounding box?\". It's actually reasonably straightforward to do so, but it requires having some knowledge on exploiting math to get the values we need. For bounding boxes, we aren't actually interested in the curve itself, but only in its \"extremities\": the minimum and maximum values the curve has for its x- and y-axis values. If you remember your calculus (provided you ever took calculus, otherwise it's going to be hard to remember) we can determine function extremities using the first derivative of that function, but this poses a problem, since our function is parametric: every axis has its own function."),a.createElement("p",null,"The solution: compute the derivative for each axis separately, and then fit them back together in the same way we do for the original."),a.createElement("p",null,"Let's look at how a parametric B\xE9zier curve \"splits up\" into two normal functions, one for the x-axis and one for the y-axis. Note the leftmost figure is again an interactive curve, without labeled axes (you get coordinates in the graph instead). The center and rightmost figures are the component functions for computing the x-axis value, given a value for ",a.createElement("i",null,"t")," (between 0 and 1 inclusive), and the y-axis value, respectively."),a.createElement("p",null,"If you move points in a curve sideways, you should only see the middle graph change; likely, moving points vertically should only show a change in the right graph."),a.createElement(i,{handler:e.props.handler,section:"components",title:"Quadratic B\xE9zier curve components",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"components",title:"Cubic B\xE9zier curve components",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}))}},extremities:{locale:"en-GB",title:"Finding extremities: root finding",getContent:function(e){return a.createElement("section",{className:"extremities"},a.createElement(r,{name:"extremities",title:"Finding extremities: root finding",number:"17"}),a.createElement("p",null,"Now that we understand (well, superficially anyway) the component functions, we can find the extremities of our B\xE9zier curve by finding maxima and minima on the component functions, by solving the equations B'(t) = 0 and B''(t) = 0. That said, in the case of quadratic curves there is no B''(t), so we only need to compute B'(t) = 0. So, how do we compute the first and second derivatives? Fairly easily, actually, until our derivatives are 4th order or higher... then things get really hard. But let's start simple:"),a.createElement("h3",{id:"quadratic-curves-linear-derivatives-"},"Quadratic curves: linear derivatives."),a.createElement("p",null,"Finding the solution for \"where is this line 0\" should be trivial:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/baa66be2d93813bf9ef4aef1dbfac3db772e30e2.svg",width:"138.6",height:"109.19999999999999"}),a.createElement("p",null,"Done. And quadratic curves have no meaningful second derivative, so we're ",a.createElement("em",null,"really")," done."),a.createElement("h3",{id:"cubic-curves-the-quadratic-formula-"},"Cubic curves: the quadratic formula."),a.createElement("p",null,"The derivative of a cubic curve is a quadratic curve, and finding the roots for a quadratic B\xE9zier curve means we can apply the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Quadratic_formula"},"Quadratic formula"),". If you've seen it before, you'll remember it, and if you haven't, it looks like this:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d5882cc83b002196c8e701ad273ced103e2b4484.svg",width:"431.2",height:"42"}),a.createElement("p",null,"So, if we can express a B\xE9zier component function as a plain polynomial, we're done: we just plug in the values into the quadratic formula, check if that square root is negative or not (if it is, there are no roots) and then just compute the two values that come out (because of that plus/minus sign we get two). Any value between 0 and 1 is a root that matters for B\xE9zier curves, anything below or above that is irrelevant (because B\xE9zier curves are only defined over the interval [0,1]). So, how do we convert?"),a.createElement("p",null,"First we turn our cubic B\xE9zier function into a quadratic one, by following the rule mentioned at the end of the ",a.createElement("a",{href:"#derivatives"},"derivatives section"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/41910cd6ca7a8720bd6c35670845892aa6ec26a1.svg",width:"564.1999999999999",height:"37.8"}),a.createElement("p",null,"And then, using these ",a.createElement("em",null,"v")," values, we can find out what our ",a.createElement("em",null,"a"),", ",a.createElement("em",null,"b"),", and ",a.createElement("em",null,"c")," should be:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/292b2b9178aca5486da7e1a596e66091ba2ed282.svg",width:"330.4",height:"124.6"}),a.createElement("p",null,"This gives us thee coefficients ",a.createElement("em",null,"a"),", ",a.createElement("em",null,"b"),", and ",a.createElement("em",null,"c")," that are expressed in terms of ",a.createElement("em",null,"v")," values, where the ",a.createElement("em",null,"v")," values are just convenient expressions of our original ",a.createElement("em",null,"p")," values, so we can do some trivial substitution to get:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2de779b7b9c6aa130b9aeadbb8c46878b94920a1.svg",width:"323.4",height:"65.8"}),a.createElement("p",null,"Easy-peasy. We can now almost trivially find the roots by plugging those values into the quadratic formula. We also note that the second derivative of a cubic curve means computing the first derivative of a quadratic curve, and we just saw how to do that in the section above."),a.createElement("h3",{id:"quartic-curves-cardano-s-algorithm-"},"Quartic curves: Cardano's algorithm."),a.createElement("p",null,"Quartic\u2014fourth degree\u2014curves have a cubic function as derivative. Now, cubic functions are a bit of a problem because they're really hard to solve. But, way back in the 16",a.createElement("sup",null,"th")," century, ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Gerolamo_Cardano"},"Gerolamo Cardano")," figured out that even if the general cubic function is really hard to solve, it can be rewritten to a form for which finding the roots is \"easy\", and then the only hard part is figuring out how to go from that form to the generic form. So:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/8f4ec98ff9230cc22d0761c9b760f3672be39f61.svg",width:"266",height:"46.199999999999996"}),a.createElement("p",null,"This is easier because for the \"easier formula\" we can use ",a.createElement("a",{href:"http://www.wolframalpha.com/input/?i=t^3+%2B+pt+%2B+q"},"regular calculus")," to find the roots. (As a cubic function, however, it can have up to three roots, but two of those can be complex. For the purpose of B\xE9zier curve extremities, we can completely ignore those complex roots, since our ",a.createElement("em",null,"t")," is a plain real number from 0 to 1.)"),a.createElement("p",null,"So, the trick is to figure out how to turn the first formula into the second formula, and to then work out the maths that gives us the roots. This is explained in detail over at ",a.createElement("a",{href:"https://trans4mind.com/personal_development/mathematics/polynomials/cubicAlgebra.htm"},"Ken J. Ward's page")," for solving the cubic equation, so instead of showing the maths, I'm simply going to show the programming code for solving the cubic equation, with the complex roots getting totally ignored."),a.createElement("div",{className:"howtocode"},a.createElement("h3",{id:"implementing-cardano-s-algorithm-for-finding-all-real-roots"},"Implementing Cardano's algorithm for finding all real roots"),a.createElement("p",null,"The \"real roots\" part is fairly important, because while you cannot take a square, cube, etc. root of a negative number in the \"real\" number space (denoted with \u211D), this is perfectly fine in the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Complex_number"},"\"complex\" number")," space (denoted with \u2102). And, as it so happens, Cardano is also attributed as the first mathematician in history to have made use of complex numbers in his calculations. For this very algorithm!"),a.createElement("pre",null,"// A helper function to filter for values in the [0,1] interval:\nfunction accept(t) {\n return 0<=t && t <=1;\n}\n\n// A real-cuberoots-only function:\nfunction cuberoot(v) {\n if(v<0) return -pow(-v,1/3);\n return pow(v,1/3);\n}\n\n// Now then: given cubic coordinates {pa, pb, pc, pd} find all roots.\nfunction getCubicRoots(pa, pb, pc, pd) {\n var a = (3*pa - 6*pb + 3*pc),\n b = (-3*pa + 3*pb),\n c = pa,\n d = (-pa + 3*pb - 3*pc + pd);\n\n // do a check to see whether we even need cubic solving:\n if (approximately(d,0)) {\n // this is not a cubic curve.\n if (approximately(a,0)) {\n // in fact, this is not a quadratic curve either.\n if (approximately(b,0)) {\n // in fact in fact, there are no solutions.\n return [];\n }\n // linear solution\n return [-c / b].filter(accept);\n }\n // quadratic solution\n var q = sqrt(b*b - 4*a*c), 2a = 2*a;\n return [(q-b)/2a, (-b-q)/2a].filter(accept)\n }\n\n // at this point, we know we need a cubic solution.\n\n a /= d;\n b /= d;\n c /= d;\n\n var p = (3*b - a*a)/3,\n p3 = p/3,\n q = (2*a*a*a - 9*a*b + 27*c)/27,\n q2 = q/2,\n discriminant = q2*q2 + p3*p3*p3;\n\n // and some variables we're going to use later on:\n var u1, v1, root1, root2, root3;\n\n // three possible real roots:\n if (discriminant < 0) {\n var mp3 = -p/3,\n mp33 = mp3*mp3*mp3,\n r = sqrt( mp33 ),\n t = -q / (2*r),\n cosphi = t<-1 ? -1 : t>1 ? 1 : t,\n phi = acos(cosphi),\n crtr = cuberoot(r),\n t1 = 2*crtr;\n root1 = t1 * cos(phi/3) - a/3;\n root2 = t1 * cos((phi+2*pi)/3) - a/3;\n root3 = t1 * cos((phi+4*pi)/3) - a/3;\n return [root1, root2, root3].filter(accept);\n }\n\n // three real roots, but two of them are equal:\n if(discriminant === 0) {\n u1 = q2 < 0 ? cuberoot(-q2) : -cuberoot(q2);\n root1 = 2*u1 - a/3;\n root2 = -u1 - a/3;\n return [root1, root2].filter(accept);\n }\n\n // one real root, two complex roots\n var sd = sqrt(discriminant);\n u1 = cuberoot(sd - q2);\n v1 = cuberoot(sd + q2);\n root1 = u1 - v1 - a/3;\n return [root1].filter(accept);\n}\n")),a.createElement("p",null,"And that's it. The maths is complicated, but the code is pretty much just \"follow the maths, while caching as many values as we can to reduce recomputing things as much as possible\" and now we have a way to find all roots for a cubic function and can just move on with using that to find extremities of our curves."),a.createElement("h3",{id:"quintic-and-higher-order-curves-finding-numerical-solutions"},"Quintic and higher order curves: finding numerical solutions"),a.createElement("p",null,"The problem with this is that as the order of the curve goes up, we can't actually solve those equations the normal way. We can't take the function, and then work out what the solutions are. Not to mention that even solving a third order derivative (for a fourth order curve) is already a royal pain in the backside. We need a better solution. We need numerical approaches."),a.createElement("p",null,"That's a fancy word for saying \"rather than solve the function, treat the problem as a sequence of identical operations, the performing of which gets us closer and closer to the real answer\". As it turns out, there is a really nice numerical root-finding algorithm, called the ",a.createElement("a",{href:"http://en.wikipedia.org/wiki/Newton-Raphson"},"Newton-Raphson")," root finding method (yes, after ",a.createElement("em",null,a.createElement("a",{href:"https://en.wikipedia.org/wiki/Isaac_Newton"},"that"))," Newton), which we can make use of."),a.createElement("p",null,"The Newton-Raphson approach consists of picking a value ",a.createElement("em",null,"t")," (any value will do), and getting the corresponding value of the function at that ",a.createElement("em",null,"t")," value. For normal functions, we can treat that value as a height. If the height is zero, we're done, we have found a root. If it's not, we take the tangent of the curve at that point, and extend it until it passes the x-axis, which will be at some new point ",a.createElement("em",null,"t"),". We then repeat the procedure with this new value, and we keep doing this until we find our root."),a.createElement("p",null,"Mathematically, this means that for some ",a.createElement("em",null,"t"),", at step ",a.createElement("em",null,"n=1"),", we perform the following calculation until ",a.createElement("em",null,"f",a.createElement("sub",null,"y")),"(",a.createElement("em",null,"t"),") is zero, so that the next ",a.createElement("em",null,"t")," is the same as the one we already have:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b563256be7016370365935944308cf878cdbc29c.svg",width:"130.2",height:"47.599999999999994"}),a.createElement("p",null,"(The Wikipedia article has a decent animation for this process, so I'm not adding a sketch for that here unless there are requests for it)"),a.createElement("p",null,"Now, this works well only if we can pick good starting points, and our curve is continuously differentiable and doesn't have oscillations. Glossing over the exact meaning of those terms, the curves we're dealing with conform to those constraints, so as long as we pick good starting points, this will work. So the question is: which starting points do we pick?"),a.createElement("p",null,"As it turns out, Newton-Raphson is so blindingly fast, so we could get away with just not picking: we simply run the algorithm from ",a.createElement("em",null,"t=0")," to ",a.createElement("em",null,"t=1")," at small steps (say, 1/200",a.createElement("sup",null,"th"),") and the result will be all the roots we want. Of course, this may pose problems for high order B\xE9zier curves: 200 steps for a 200",a.createElement("sup",null,"th")," order B\xE9zier curve is going to go wrong, but that's okay: there is no reason, ever, to use B\xE9zier curves of crazy high orders. You might use a fifth order curve to get the \"nicest still remotely workable\" approximation of a full circle with a single B\xE9zier curve, that's pretty much as high as you'll ever need to go."),a.createElement("h3",{id:"in-conclusion-"},"In conclusion:"),a.createElement("p",null,"So now that we know how to do root finding, we can determine the first and second derivative roots for our B\xE9zier curves, and show those roots overlaid on the previous graphics:"),a.createElement(i,{handler:e.props.handler,section:"extremities",title:"Quadratic B\xE9zier curve extremities",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"extremities",title:"Cubic B\xE9zier curve extremities",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}))}},boundingbox:{locale:"en-GB",title:"Bounding boxes",getContent:function(e){return a.createElement("section",{className:"boundingbox"},a.createElement(r,{name:"boundingbox",title:"Bounding boxes",number:"18"}),a.createElement("p",null,"If we have the extremities, and the start/end points, a simple for loop that tests for min/max values for x and y means we have the four values we need to box in our curve:"),a.createElement("p",null,a.createElement("em",null,"Computing the bounding box for a B\xE9zier curve"),":"),a.createElement("ol",null,a.createElement("li",null,"Find all ",a.createElement("em",null,"t")," value(s) for the curve derivative's x- and y-roots."),a.createElement("li",null,"Discard any ",a.createElement("em",null,"t")," value that's lower than 0 or higher than 1, because B\xE9zier curves only use the interval [0,1]."),a.createElement("li",null,"Determine the lowest and highest value when plugging the values ",a.createElement("em",null,"t=0"),", ",a.createElement("em",null,"t=1")," and each of the found roots into the original functions: the lowest value is the lower bound, and the highest value is the upper bound for the bounding box we want to construct.")),a.createElement("p",null,"Applying this approach to our previous root finding, we get the following bounding boxes (with all curve extremity points shown on the curve):"),a.createElement(i,{handler:e.props.handler,section:"boundingbox",title:"Quadratic B\xE9zier bounding box",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"boundingbox",title:"Cubic B\xE9zier bounding box",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}),a.createElement("p",null,"We can construct even nicer boxes by aligning them along our curve, rather than along the x- and y-axis, but in order to do so we first need to look at how aligning works."))}},aligning:{locale:"en-GB",title:"Aligning curves",getContent:function(e){return a.createElement("section",{className:"aligning"},a.createElement(r,{name:"aligning",title:"Aligning curves",number:"19"}),a.createElement("p",null,"While there are an incredible number of curves we can define by varying the x- and y-coordinates for the control points, not all curves are actually distinct. For instance, if we define a curve, and then rotate it 90 degrees, it's still the same curve, and we'll find its extremities in the same spots, just at different draw coordinates. As such, one way to make sure we're working with a \"unique\" curve is to \"axis-align\" it."),a.createElement("p",null,"Aligning also simplifies a curve's functions. We can translate (move) the curve so that the first point lies on (0,0), which turns our ",a.createElement("em",null,"n")," term polynomial functions into ",a.createElement("em",null,"n-1")," term functions. The order stays the same, but we have less terms. Then, we can rotate the curves so that the last point always lies on the x-axis, too, making its coordinate (...,0). This further simplifies the function for the y-component to an ",a.createElement("em",null,"n-2")," term function. For instance, if we have a cubic curve such as this:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d253dc7ff011a8ae46f3351975f1d4beedd7a794.svg",width:"499.79999999999995",height:"42"}),a.createElement("p",null,"Then translating it so that the first coordinate lies on (0,0), moving all ",a.createElement("em",null,"x")," coordinates by -120, and all ",a.createElement("em",null,"y")," coordinates by -160, gives us:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b3ec747086a146c1b2c682afea6b1eae016c9a7a.svg",width:"482.99999999999994",height:"42"}),a.createElement("p",null,"If we then rotate the curve so that its end point lies on the x-axis, the coordinates (integer-rounded for illustrative purposes here) become:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/4ae08c9737557d1504f8e4e7bd06720b31313e09.svg",width:"474.59999999999997",height:"42"}),a.createElement("p",null,"If we drop all the zero-terms, this gives us:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2ca4160d7463ef308c4d41b340ba77b8e9cd08b5.svg",width:"406",height:"42"}),a.createElement("p",null,"We can see that our original curve definition has been simplified considerably. The following graphics illustrate the result of aligning our example curves to the x-axis, with the cubic case using the coordinates that were just used in the example formulae:"),a.createElement(i,{handler:e.props.handler,section:"aligning",title:"Aligning a quadratic curve",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"aligning",title:"Aligning a cubic curve",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}))}},tightbounds:{locale:"en-GB",title:"Tight boxes",getContent:function(e){return a.createElement("section",{className:"tightbounds"},a.createElement(r,{name:"tightbounds",title:"Tight boxes",number:"20"}),a.createElement("p",null,"With our knowledge of bounding boxes, and curve alignment, We can now form the \"tight\" bounding box for curves. We first align our curve, recording the translation we performed, \"T\", and the rotation angle we used, \"R\". We then determine the aligned curve's normal bounding box. Once we have that, we can map that bounding box back to our original curve by rotating it by -R, and then translating it by -T. We now have nice tight bounding boxes for our curves:"),a.createElement(i,{handler:e.props.handler,section:"tightbounds",title:"Aligning a quadratic curve",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"tightbounds",title:"Aligning a cubic curve",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}),a.createElement("p",null,"These are, strictly speaking, not necessarily the tightest possible bounding boxes. It is possible to compute the optimal bounding box by determining which spanning lines we need to effect a minimal box area, but because of the parametric nature of B\xE9zier curves this is actually a rather costly operation, and the gain in bounding precision is often not worth it. If there is high demand for it, I'll add a section on how to precisely compute the best fit bounding box, but the maths is fairly grueling and just not really worth spending time on."))}},inflections:{locale:"en-GB",title:"Curve inflections",getContent:function(e){return a.createElement("section",{className:"inflections"},a.createElement(r,{name:"inflections",title:"Curve inflections",number:"21"}),a.createElement("p",null,"Now that we know how to align a curve, there's one more thing we can calculate: inflection points. Imagine we have a variable size circle that we can slide up against our curve. We place it against the curve and adjust its radius so that where it touches the curve, the curvatures of the curve and the circle are the same, and then we start to slide the circle along the curve - for quadratic curves, we can always do this without the circle behaving oddly: we might have to change the radius of the circle as we slide it along, but it'll always sit against the same side of the curve."),a.createElement("p",null,"But what happens with cubic curves? Imagine we have an S curve and we place our circle at the start of the curve, and start sliding it along. For a while we can simply adjust the radius and things will be fine, but once we get to the midpoint of that S, something odd happens: the circle \"flips\" from one side of the curve to the other side, in order for the curvatures to keep matching. This is called an inflection, and we can find out where those happen relatively easily."),a.createElement("p",null,"What we need to do is solve a simple equation:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b039194e01b6081628efaf4aa169a4c50fa4aae4.svg",width:"61.599999999999994",height:"16.799999999999997"}),a.createElement("p",null,"What we're saying here is that given the curvature function ",a.createElement("em",null,"C(t)"),", we want to know for which values of ",a.createElement("em",null,"t")," this function is zero, meaning there is no \"curvature\", which will be exactly at the point between our circle being on one side of the curve, and our circle being on the other side of the curve. So what does ",a.createElement("em",null,"C(t)")," look like? Actually something that seems not too hard:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/297d1e13000b19d351e5884a40909652a2ee83e2.svg",width:"404.59999999999997",height:"22.4"}),a.createElement("p",null,"The function ",a.createElement("em",null,"C(t)")," is the cross product between the first and second derivative functions for the parametric dimensions of our curve. And, as already shown, derivatives of B\xE9zier curves are just simpler B\xE9zier curves, with very easy to compute new coefficients, so this should be pretty easy."),a.createElement("p",null,"However as we've seen in the section on aligning, aligning lets us simplify things ",a.createElement("em",null,"a lot"),", by completely removing the contributions of the first coordinate from most mathematical evaluations, and removing the last ",a.createElement("em",null,"y")," coordinate as well by virtue of the last point lying on the x-axis. So, while we can evaluate ",a.createElement("em",null,"C(t) = 0")," for our curve, it'll be much easier to first axis-align the curve and ",a.createElement("em",null,"then")," evaluating the curvature function."),a.createElement("div",{className:"note"},a.createElement("h3",{id:"let-s-derive-the-full-formula-anyway"},"Let's derive the full formula anyway"),a.createElement("p",null,"Of course, before we do our aligned check, let's see what happens if we compute the curvature function without axis-aligning. We start with the first and second derivatives, given our basis functions:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/be2120595f2acf83d88f4ddc30a8b4b17367907e.svg",width:"631.4",height:"74.19999999999999"}),a.createElement("p",null,"And of course the same functions for ",a.createElement("em",null,"y"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f204a9dc34913f1ee2c2f7450c640aae916f6714.svg",width:"418.59999999999997",height:"72.8"}),a.createElement("p",null,"Asking a computer to now compose the ",a.createElement("em",null,"C(t)")," function for us (and to expand it to a readable form of simple terms) gives us this rather overly complicated set of arithmetic expressions:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/0e69d797dc67f0bd2d826fcf8c48c22ff5decf23.svg",width:"579.5999999999999",height:"102.19999999999999"}),a.createElement("p",null,"That is... unwieldy. So, we note that there are a lot of terms that involve multiplications involving x1, y1, and y4, which would all disappear if we axis-align our curve, which is why aligning is a great idea.")),a.createElement("p",null,"Aligning our curve so that three of the eight coefficients become zero, we end up with the following simple term function for ",a.createElement("em",null,"C(t)"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f61c01094f0de8ca4c7f26a229f0206d54b13930.svg",width:"588",height:"22.4"}),a.createElement("p",null,"That's a lot easier to work with: we see a fair number of terms that we can compute and then cache, giving us the following simplification:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c1e427616a8a2502abf3cf46415971d0df9a273c.svg",width:"534.8",height:"77"}),a.createElement("p",null,"This is a plain quadratic curve, and we know how to solve ",a.createElement("em",null,"C(t) = 0"),"; we use the quadratic formula:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/368099657b735b0d17becbbe7be915e88e8c04c5.svg",width:"456.4",height:"57.4"}),a.createElement("p",null,"We can easily compute this value ",a.createElement("em",null,"if")," the discriminator isn't a negative number (because we only want real roots, not complex roots), and ",a.createElement("em",null,"if")," ",a.createElement("em",null,"x")," is not zero, because divisions by zero are rather useless."),a.createElement("p",null,"Taking that into account, we compute ",a.createElement("em",null,"t"),", we disregard any ",a.createElement("em",null,"t")," value that isn't in the B\xE9zier interval [0,1], and we now know at which ",a.createElement("em",null,"t")," value(s) our curve will inflect."),a.createElement(i,{handler:e.props.handler,section:"inflections",title:"Finding cubic B\xE9zier curve inflections",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}))}},canonical:{locale:"en-GB",title:"Canonical form (for cubic curves)",getContent:function(e){return a.createElement("section",{className:"canonical"},a.createElement(r,{name:"canonical",title:"Canonical form (for cubic curves)",number:"22"}),a.createElement("p",null,"While quadratic curves are relatively simple curves to analyze, the same cannot be said of the cubic curve. As a curvature is controlled by more than one control point, it exhibits all kinds of features like loops, cusps, odd colinear features, and as many as two inflection points because the curvature can change direction up to three times. Now, knowing what kind of curve we're dealing with means that some algorithms can be run more efficiently than if we have to implement them as generic solvers, so is there a way to determine the curve type without lots of work?"),a.createElement("p",null,"As it so happens, the answer is yes, and the solution we're going to look at was presented by Maureen C. Stone from Xerox PARC and Tony D. deRose from the University of Washington in their joint paper ",a.createElement("a",{href:"http://graphics.pixar.com/people/derose/publications/CubicClassification/paper.pdf"},"\"A Geometric Characterization of Parametric Cubic curves\""),". It was published in 1989, and defines curves as having a \"canonical\" form (i.e. a form that all curves can be reduced to) from which we can immediately tell what features a curve will have. So how does it work?"),a.createElement("p",null,"The first observation that makes things work is that if we have a cubic curve with four points, we can apply a linear transformation to these points such that three of the points end up on (0,0), (0,1) and (1,1), with the last point then being \"somewhere\". After applying that transformation, the location of that last point can then tell us what kind of curve we're dealing with. Specifically, we see the following breakdown:"),a.createElement(i,{handler:e.props.handler,section:"canonical",static:!0,title:"The canonical curve map",setup:e.setup,sname:"setup",draw:e.drawBase,dname:"drawBase"}),a.createElement("p",null,"This is a fairly funky image, so let's see how it breaks down. We see the three fixed points at (0,0), (0,1) and (1,1), and then the fourth point is somewhere. Depending on where it is, our curve will have certain features. Namely, if the fourth point is..."),a.createElement("ol",null,a.createElement("li",null,"anywhere on and in the red zone, the curve will either be self-intersecting (yielding a loop), or it will have a sharp discontinuity (yielding a cusp). Anywhere inside the red zone, this will be a loop. We won't know ",a.createElement("em",null,"where")," that loop is (in terms of ",a.createElement("em",null,"t")," values), but we are guaranteed that there is one."),a.createElement("li",null,"on the left (red) edge, the curve will have a cusp. We again don't know ",a.createElement("em",null,"where"),", just that it has one. This edge is described by the function:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ae5a63e86bb367e6266a394962387344d0a92b10.svg",width:"189",height:"39.199999999999996"}),a.createElement("ol",{start:"3"},a.createElement("li",null,"on the lower right (pink) edge, the curve will have a loop at t=1, so we know the end coordinate of the curve also lies ",a.createElement("em",null,"on")," the curve. This edge is described by the function:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d389fcde05a773be99f84db5fc9ed7ef043bf406.svg",width:"242.2",height:"40.599999999999994"}),a.createElement("ol",{start:"4"},a.createElement("li",null,"on the top (blue) edge, the curve will have a loop at t=0, so we know the start coordinate of the curve also lies ",a.createElement("em",null,"on")," the curve. This edge is described by the function:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d97181a9d0ada19862a0ff2cebb08bdee00868d7.svg",width:"161",height:"39.199999999999996"}),a.createElement("ol",{start:"5"},a.createElement("li",null,"inside the green zone, the curve will have a single inflection, switching concave/convex once."),a.createElement("li",null,"between the red and green zones, the curve has two inflections, meaning its curvature switches between concave/convex form twice."),a.createElement("li",null,"anywhere on the right of the red zone, the curve will have no inflections. It'll just be a well-behaved arch.")),a.createElement("p",null,"Of course, this map is fairly small, but the regions extend to infinity, with well defined boundaries."),a.createElement("div",{className:"note"},a.createElement("h3",{id:"wait-where-do-those-lines-come-from-"},"Wait, where do those lines come from?"),a.createElement("p",null,"Without repeating the paper mentioned at the top of this section, the loop-boundaries come from rewriting the curve into canonical form, and then solving the formulae for which constraints must hold for which possible curve properties. In the paper these functions yield formulae for where you will find cusp points, or loops where we know t=0 or t=1, but those functions are derived for the full cubic expression, meaning they apply to t=-\u221E to t=\u221E... For B\xE9zier curves we only care about the \"clipped interval\" t=0 to t=1, so some of the properties that apply when you look at the curve over an infinite interval simply don't apply to the B\xE9zier curve interval."),a.createElement("p",null,"The right bound for the loop region, indicating where the curve switches from \"having inflections\" to \"having a loop\", for the general cubic curve, is actually mirrored over x=1, but for B\xE9zier curves this right half doesn't apply, so we don't need to pay attention to it. Similarly, the boundaries for t=0 and t=1 loops are also nice clean curves but get \"cut off\" when we only look at what the general curve does over the interval t=0 to t=1."),a.createElement("p",null,"For the full details, head over to the paper and read through sections 3 and 4. If you still remember your high school precalculus, you can probably follow along with this paper, although you might have to read it a few times before all the bits \"click\".")),a.createElement("p",null,"So now the question becomes: how do we manipulate our curve so that it fits this canonical form, with three fixed points, and one \"free\" point? Enter linear algebra. Don't worry, I'll be doing all the math for you, as well as show you what the effect is on our curves, but basically we're going to be using linear algebra, rather than calculus, because \"it's way easier\". Sometimes a calculus approach is very hard to work with, when the equivalent geometrical solution is super obvious."),a.createElement("p",null,"The approach is going to start with a curve that doesn't have all-colinear points (so we need to make sure the points don't all fall on a straight line), and then applying four graphics operations that you will probably have heard of: translation (moving all points by some fixed x- and y-distance), scaling (multiplying all points by some x and y scale factor), and shearing (an operation that turns rectangles into parallelograms)."),a.createElement("p",null,"Step 1: we translate any curve by -p1.x and -p1.y, so that the curve starts at (0,0). We're going to make use of an interesting trick here, by pretending our 2D coordinates are 3D, with the ",a.createElement("em",null,"z")," coordinate simply always being 1. This is an old trick in graphics to overcome the limitations of 2D transformations: without it, we can only turn (x,y) coordinates into new coordinates of the form (ax + by, cx + dy), which means we can't do translation, since that requires we end up with some kind of (x + a, y + b). If we add a bogus ",a.createElement("em",null,"z")," coordinate that is always 1, then we can suddenly add arbitrary values. For example:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/00ca2970fccea8f0883af6db4fbc3a60efd2539d.svg",width:"495.59999999999997",height:"57.4"}),a.createElement("p",null,"Sweet! ",a.createElement("em",null,"z")," stays 1, so we can effectively ignore it entirely, but we added some plain values to our x and y coordinates. So, if we want to subtract p1.x and p1.y, we use:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/1a48a27661f19f066ddd591fb4fc0d553b34c944.svg",width:"477.4",height:"60.199999999999996"}),a.createElement("p",null,"Running all our coordinates through this transformation gives a new set of coordinates, let's call those ",a.createElement("strong",null,"U"),", where the first coordinate lies on (0,0), and the rest is still somewhat free. Our next job is to make sure point 2 ends up lying on the ",a.createElement("em",null,"x=0")," line, so what we want is a transformation matrix that, when we run it, subtracts ",a.createElement("em",null,"x")," from whatever ",a.createElement("em",null,"x")," we currently have. This is called ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Shear_matrix"},"shearing"),", and the typical x-shear matrix and its transformation looks like this:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/8e98c870c9d5b60bccf196d29e290f9de6657ce7.svg",width:"204.39999999999998",height:"56"}),a.createElement("p",null,"So we want some shearing value that, when multiplied by ",a.createElement("em",null,"y"),", yields ",a.createElement("em",null,"-x"),", so our x coordinate becomes zero. That value is simply ",a.createElement("em",null,"-x/y"),", because ",a.createElement("em",null,"-x/y ")," y = -x*. Done:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/585fa88864a98008c15225bdbeb0eb26a4653dab.svg",width:"140",height:"70"}),a.createElement("p",null,"Now, running this on all our points generates a new set of coordinates, let's call those ",a.createElement("strong",null,"V"),", which now have point 1 on (0,0) and point 2 on (0, some-value), and we wanted it at (0,1), so we need to ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Scaling_%28geometry%29"},"do some scaling")," to make sure it ends up at (0,1). Additionally, we want point 3 to end up on (1,1), so we can also scale x to make sure its x-coordinate will be 1 after we run the transform. That means we'll be x-scaling by 1/point3",a.createElement("sub",null,"x"),", and y-scaling by point2",a.createElement("sub",null,"y"),". This is really easy:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/bf9c60b59e6247de3fece63638a8333bdcd068a4.svg",width:"144.2",height:"74.19999999999999"}),a.createElement("p",null,"Then, finally, this generates a new set of coordinates, let's call those W, of which point 1 lies on (0,0), point 2 lies on (0,1), and point three lies on (1, ...) so all that's left is to make sure point 3 ends up at (1,1) - but we can't scale! Point 2 is already in the right place, and y-scaling would move it out of (0,1) again, so our only option is to y-shear point three, just like how we x-sheared point 2 earlier. In this case, we do the same trick, but with ",a.createElement("code",null,"y/x")," rather than ",a.createElement("code",null,"x/y")," because we're not x-shearing but y-shearing. Additionally, we don't actually want to end up at zero (which is what we did before) so we need to shear towards an offset, in this case 1:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/af412fd7df7faf35973314095ec6bf1cb28a8e34.svg",width:"147",height:"68.6"}),a.createElement("p",null,"And this generates our final set of four coordinates. Of these, we already know that points 1 through 3 are (0,0), (0,1) and (1,1), and only the last coordinate is \"free\". In fact, given any four starting coordinates, the resulting \"transformation mapped\" coordinate will be:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/66e084e9ee396b8cc40de3d0df9c4658dcd10e14.svg",width:"477.4",height:"95.19999999999999"}),a.createElement("p",null,"That looks very complex, but notice that every coordinate value is being offset by the initial translation, and a lot of terms in there repeat: it's pretty easy to calculate this fast, since there's so much we can cache and reuse while we compute this mapped coordinate!"),a.createElement("p",null,"First, let's just do that translation step as a \"preprocessing\" operation so we don't have to subtract the values all the time. What does that leave?"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d2dc58a4a6951ff27e5b83fb9be239e2fbe0f7ce.svg",width:"371",height:"61.599999999999994"}),a.createElement("p",null,"Suddenly things look a lot simpler: the mapped x is fairly straight forward to compute, and we see that the mapped y actually contains the mapped x in its entirety, so we'll have that part already available when we need to evaluate it. In fact, let's pull out all those common factors to see just how simple this is:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ebaea590e50dfce555e8ad2c63682fe9e6285f06.svg",width:"428.4",height:"42"}),a.createElement("p",null,"That's kind of super-simple to write out in code, I think you'll agree. Coding math tends to be easier than the formulae initially make it look!"),a.createElement("div",{className:"note"},a.createElement("h3",{id:"how-do-you-track-all-that-"},"How do you track all that?"),a.createElement("p",null,"Doing maths can be a pain, so whenever possible, I like to make computers do the work for me. Especially for things like this, I simply use ",a.createElement("a",{href:"http://www.wolfram.com/mathematica"},"Mathematica"),". Tracking all this math by hand is insane, and we invented computers, literally, to do this for us. I have no reason to use pen and paper when I can write out what I want to do in a program, and have the program do the math for me. And real math, too, with symbols, not with numbers. In fact, ",a.createElement("a",{href:"http://pomax.github.io/gh-weblog-2/downloads/canonical-curve.nb"},"here's")," the Mathematica notebook if you want to see how this works for yourself."),a.createElement("p",null,"Now, I know, you're thinking \"but Mathematica is super expensive!\" and that's true, it's ",a.createElement("a",{href:"http://www.wolfram.com/mathematica-home-edition"},"$295 for home use"),", but it's ",a.createElement("strong",null,"also")," ",a.createElement("a",{href:"http://www.wolfram.com/raspberry-pi"},"free when you buy a $35 raspberry pi"),". Obviously, I bought a raspberry pi, and I encourage you to do the same. With that, as long as you know what you want to ",a.createElement("em",null,"do"),", Mathematica can just do it for you. And we don't have to be geniuses to work out what the maths looks like. That's what we have computers for.")),a.createElement("p",null,"So, let's write up a sketch that'll show us the canonical form for any curve drawn in blue, overlaid on our canonical map, so that we can immediately tell which features our curve must have, based on where the fourth coordinate is located on the map:"),a.createElement(i,{handler:e.props.handler,section:"canonical",title:"A cubic curve mapped to canonical form",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw"}))}},yforx:{locale:"en-GB",title:"Finding Y, given X",getContent:function(e){return a.createElement("section",{className:"yforx"},a.createElement(r,{name:"yforx",title:"Finding Y, given X",number:"23"}),a.createElement("p",null,"One common task that pops up in things like CSS work, or parametric equalisers, or image leveling, or any other number of applications where Bezier curves are used as control curves in a way that there is really only ever one \"y\" value associated with one \"x\" value, you might want to cut out the middle man, as it were, and compute \"y\" directly based on \"x\". After all, the function looks simple enough, finding the \"y\" value should be simple too, right? Unfortunately, not really. However, it _is_ possible and as long as you have some code in place to help, it's not a lot of a work either."),a.createElement("p",null,"We'll be tackling this problem in two stages: the first, which is the hard part, is figuring out which \"t\" value belongs to any given \"x\" value. For instance, have a look at the following graphic. On the left we have a Bezier curve that looks for all intents and purposes like it fits our criteria: every \"x\" has one and only one associated \"y\" value. On the right we see the function for just the \"x\" values: that's a cubic curve, but not a really crazy cubic curve. If you mouse over the graphic, you will see a red line drawn that corresponds to the ",a.createElement("code",null,"x")," coordinate under your cursor: vertical in the left graphic, horizontal in the right."),a.createElement(i,{handler:e.props.handler,section:"yforx",title:"Finding t, given x=x(t). Left: our curve, right: the x=x(t) function",setup:e.tforx.setup,draw:e.tforx.draw,onMouseMove:e.onMouseMove}),a.createElement("p",null,"Now, if you look more closely at that right graphic, you'll notice something interesting: if we treat the red line as \"the x axis\", then the point where the function crosses our line is really just a root for the cubic function x(t). So... can we just use root finding to get the \"t\" value associated with an \"x\" value? To which the answer should unsurprisingly be \" yes, we can\". Sure, we'll need to compute cubic roots, but we've already seen how to do that in the section on ",a.createElement("a",{href:"#extremities"},"finding extremities"),", and we're not dealing with a complicated case: we ",a.createElement("em",null,"know")," there is only root, so let's go and find it!"),a.createElement("p",null,"First, let's look at the function for x(t):"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d6c450b507c40d0d5b24577b842006a27081f59d.svg",width:"351.4",height:"19.599999999999998"}),a.createElement("p",null,"We can rewrite this to a plain polynomial form, by just fully writing out the expansion and then collecting the polynomial factors, as:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b3383dc41a18c3e7a10c123112e7d748d9d10181.svg",width:"467.59999999999997",height:"19.599999999999998"}),a.createElement("p",null,"Nothing special here: that's a standard cubic polynomial in \"power\" form (i.e. all the terms are ordered by their power of ",a.createElement("code",null,"t"),"). So, given that ",a.createElement("code",null,"a"),", ",a.createElement("code",null,"b"),", ",a.createElement("code",null,"c"),", ",a.createElement("code",null,"d"),", ",a.createElement("em",null,"and")," ",a.createElement("code",null,"x(t)")," are all known constants, we can trivially rewrite this (by moving the ",a.createElement("code",null,"x(t)")," across the equal sign) as:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/16ff897603ba2d11ae6cd84eeac93e8e9b56f44d.svg",width:"488.59999999999997",height:"19.599999999999998"}),a.createElement("p",null,"You might be wondering \"where did all the other 'minus x' for all the other values a, b, c, and d go?\" and the answer there is that they all cancel out, so the only one we actually need to subtract is the one at the end. Handy! So now we just... solve this equation: we know everything except ",a.createElement("code",null,"t"),", we just need some mathematical insight to tell us how to do this."),a.createElement("p",null,"...Of course \"just\" is not the right qualifier here, there is nothing \"just\" about finding the roots of a cubic function, but thankfully we've already covered the tool to do this in the ",a.createElement("a",{href:"#extremities"},"root finding")," section: Gerolano Cardano's solution for cubic roots. Of course, we still need to be a bit careful, because cubic roots are complicated things: you can get up to three roots back, even though we only \"want\" one root. In our case, only one will be both a real number (as opposed to a complex number) ",a.createElement("em",null,"and")," lie in the ",a.createElement("code",null,"t")," interval [0,1], so we need to filter for that:"),a.createElement("pre",null,"double x = some value we know!\ndouble[] roots = getTforX(x);\ndouble t;\nif (roots.length > 0) {\n for (double _t: roots) {\n if (_t<0 || _t>1) continue;\n t = _t;\n break;\n }\n}\n"),a.createElement("p",null,"And that's it, we're done: we now have the ",a.createElement("code",null,"t")," value corresponding to our ",a.createElement("code",null,"x"),", and we can just evaluate our curve for that ",a.createElement("code",null,"t")," value to find a coordinate that has our original, known ",a.createElement("code",null,"x"),", and our unknown ",a.createElement("code",null,"y")," value. Mouse over the following graphic, which performs this root finding based on a knowledge of which \"x\" value we're interested in."),a.createElement(i,{handler:e.props.handler,section:"yforx",title:"Finding y(t), by finding t, given x=x(t)",setup:e.yforx.setup,draw:e.yforx.draw,onMouseMove:e.onMouseMove}))}},arclength:{locale:"en-GB",title:"Arc length",getContent:function(e){return a.createElement("section",{className:"arclength"},a.createElement(r,{name:"arclength",title:"Arc length",number:"24"}),a.createElement("p",null,"How long is a B\xE9zier curve? As it turns out, that's not actually an easy question, because the answer requires maths that \u2014much like root finding\u2014 cannot generally be solved the traditional way. If we have a parametric curve with ",a.createElement("em",null,"f",a.createElement("sub",null,"x"),"(t)")," and ",a.createElement("em",null,"f",a.createElement("sub",null,"y"),"(t)"),", then the length of the curve, measured from start point to some point ",a.createElement("em",null,"t = z"),", is computed using the following seemingly straight forward (if a bit overwhelming) formula:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/16e3f81dfc12c526ca53b477b2aa67ef7b56bfe2.svg",width:"147",height:"35"}),a.createElement("p",null,"or, more commonly written using Leibnitz notation as:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/8e2857c32b23969bca67b0ead318493a3e61dc4a.svg",width:"257.59999999999997",height:"36.4"}),a.createElement("p",null,"This formula says that the length of a parametric curve is in fact equal to the ",a.createElement("strong",null,"area")," underneath a function that looks a remarkable amount like Pythagoras' rule for computing the diagonal of a straight angled triangle. This sounds pretty simple, right? Sadly, it's far from simple... cutting straight to after the chase is over: for quadratic curves, this formula generates an ",a.createElement("a",{href:"http://www.wolframalpha.com/input/?i=antiderivative+for+sqrt%28%282*%281-t%29*t*B+%2B+t%5E2*C%29%27%5E2+%2B+%282*%281-t%29*t*E%29%27%5E2%29&incParTime=true"},"unwieldy computation"),", and we're simply not going to implement things that way. For cubic B\xE9zier curves, things get even more fun, because there is no \"closed form\" solution, meaning that due to the way calculus works, there is no generic formula that allows you to calculate the arc length. Let me just repeat this, because it's fairly crucial: ",a.createElement("strong",null,a.createElement("em",null,"for cubic and higher B\xE9zier curves, there is no way to solve this function if you want to use it \"for all possible coordinates\"")),"."),a.createElement("p",null,"Seriously: ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Abel%E2%80%93Ruffini_theorem"},"It cannot be done"),"."),a.createElement("p",null,"So we turn to numerical approaches again. The method we'll look at here is the ",a.createElement("a",{href:"http://www.youtube.com/watch?v=unWguclP-Ds&feature=BFa&list=PLC8FC40C714F5E60F&index=1"},"Gauss quadrature"),". This approximation is a really neat trick, because for any ",a.createElement("em",null,"n",a.createElement("sup",null,"th"))," degree polynomial it finds approximated values for an integral really efficiently. Explaining this procedure in length is way beyond the scope of this page, so if you're interested in finding out why it works, I can recommend the University of South Florida video lecture on the procedure, linked in this very paragraph. The general solution we're looking for is the following:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b895b77808483a06908db7499619642b06ab5bff.svg",width:"667.8",height:"74.19999999999999"}),a.createElement("p",null,"In plain text: an integral function can always be treated as the sum of an (infinite) number of (infinitely thin) rectangular strips sitting \"under\" the function's plotted graph. To illustrate this idea, the following graph shows the integral for a sinusoid function. The more strips we use (and of course the more we use, the thinner they get) the closer we get to the true area under the curve, and thus the better the approximation:"),a.createElement("div",{className:"figure"},a.createElement(i,{handler:e.props.handler,section:"arclength",inline:!0,static:!0,title:"A function's approximated integral",setup:e.setup,sname:"setup",draw:e.drawCoarseIntegral,dname:"drawCoarseIntegral"}),a.createElement(i,{handler:e.props.handler,section:"arclength",inline:!0,static:!0,title:"A better approximation",setup:e.setup,sname:"setup",draw:e.drawFineIntegral,dname:"drawFineIntegral"}),a.createElement(i,{handler:e.props.handler,section:"arclength",inline:!0,static:!0,title:"An even better approximation",setup:e.setup,sname:"setup",draw:e.drawSuperFineIntegral,dname:"drawSuperFineIntegral"})),a.createElement("p",null,"Now, infinitely many terms to sum and infinitely thin rectangles are not something that computers can work with, so instead we're going to approximate the infinite summation by using a sum of a finite number of \"just thin\" rectangular strips. As long as we use a high enough number of thin enough rectangular strips, this will give us an approximation that is pretty close to what the real value is."),a.createElement("p",null,"So, the trick is to come up with useful rectangular strips. A naive way is to simply create ",a.createElement("em",null,"n")," strips, all with the same width, but there is a far better way using special values for ",a.createElement("em",null,"C")," and ",a.createElement("em",null,"f(t)")," depending on the value of ",a.createElement("em",null,"n"),", which indicates how many strips we'll use, and it's called the Legendre-Gauss quadrature."),a.createElement("p",null,"This approach uses strips that are ",a.createElement("em",null,"not")," spaced evenly, but instead spaces them in a special way based on describing the function as a polynomial (the more strips, the more accurate the polynomial), and then computing the exact integral for that polynomial. We're essentially performing arc length computation on a flattened curve, but flattening it based on the intervals dictated by the Legendre-Gauss solution."),a.createElement("div",{className:"note"},a.createElement("p",null,"Note that one requirement for the approach we'll use is that the integral must run from -1 to 1. That's no good, because we're dealing with B\xE9zier curves, and the length of a section of curve applies to values which run from 0 to \"some value smaller than or equal to 1\" (let's call that value ",a.createElement("em",null,"z"),"). Thankfully, we can quite easily transform any integral interval to any other integral interval, by shifting and scaling the inputs. Doing so, we get the following:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/631e6396082d9621472546b87c2e27065990d568.svg",width:"358.4",height:"75.6"}),a.createElement("p",null,"That may look a bit more complicated, but the fraction involving ",a.createElement("em",null,"z")," is a fixed number, so the summation, and the evaluation of the ",a.createElement("em",null,"f(t)")," values are still pretty simple."),a.createElement("p",null,"So, what do we need to perform this calculation? For one, we'll need an explicit formula for ",a.createElement("em",null,"f(t)"),", because that derivative notation is handy on paper, but not when we have to implement it. We'll also need to know what these ",a.createElement("em",null,"C",a.createElement("sub",null,"i"))," and ",a.createElement("em",null,"t",a.createElement("sub",null,"i"))," values should be. Luckily, that's less work because there are actually many tables available that give these values, for any ",a.createElement("em",null,"n"),", so if we want to approximate our integral with only two terms (which is a bit low, really) then ",a.createElement("a",{href:"legendre-gauss.html"},"these tables")," would tell us that for ",a.createElement("em",null,"n=2")," we must use the following values:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/6dc4299695f03c27c362e7faf47ae4474794809e.svg",width:"65.8",height:"98"}),a.createElement("p",null,"Which means that in order for us to approximate the integral, we must plug these values into the approximate function, which gives us:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/fe54606651e308caf83a65e53bc4d6104f8a4ee1.svg",width:"499.79999999999995",height:"46.199999999999996"}),a.createElement("p",null,"We can program that pretty easily, provided we have that ",a.createElement("em",null,"f(t)")," available, which we do, as we know the full description for the B\xE9zier curve functions B",a.createElement("sub",null,"x"),"(t) and B",a.createElement("sub",null,"y"),"(t).")),a.createElement("p",null,"If we use the Legendre-Gauss values for our ",a.createElement("em",null,"C")," values (thickness for each strip) and ",a.createElement("em",null,"t")," values (location of each strip), we can determine the approximate length of a B\xE9zier curve by computing the Legendre-Gauss sum. The following graphic shows a cubic curve, with its computed lengths; Go ahead and change the curve, to see how its length changes. One thing worth trying is to see if you can make a straight line, and see if the length matches what you'd expect. What if you form a line with the control points on the outside, and the start/end points on the inside?"),a.createElement(i,{handler:e.props.handler,section:"arclength",title:"Arc length for a B\xE9zier curve",setup:e.setupCurve,sname:"setupCurve",draw:e.drawCurve,dname:"drawCurve"}))}},arclengthapprox:{locale:"en-GB",title:"Approximated arc length",getContent:function(e){return a.createElement("section",{className:"arclengthapprox"},a.createElement(r,{name:"arclengthapprox",title:"Approximated arc length",number:"25"}),a.createElement("p",null,"Sometimes, we don't actually need the precision of a true arc length, and we can get away with simply computing the approximate arc length instead. The by far fastest way to do this is to flatten the curve and then simply calculate the linear distance from point to point. This will come with an error, but this can be made arbitrarily small by increasing the segment count."),a.createElement("p",null,"If we combine the work done in the previous sections on curve flattening and arc length computation, we can implement these with minimal effort:"),a.createElement(i,{handler:e.props.handler,section:"arclengthapprox",title:"Approximate quadratic curve arc length",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}),a.createElement(i,{handler:e.props.handler,section:"arclengthapprox",title:"Approximate cubic curve arc length",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}),a.createElement("p",null,"Try clicking on the sketch and using your up and down arrow keys to lower the number of segments for both the quadratic and cubic curve. You may notice that the error in length is actually pretty significant, even if the percentage is fairly low: if the number of segments used yields an error of 0.1% or higher, the flattened curve already looks fairly obviously flattened. And of course, the longer the curve, the more significant the error will be."))}},curvature:{locale:"en-GB",title:"Curvature of a curve",getContent:function(e){return a.createElement("section",{className:"curvature"},a.createElement(r,{name:"curvature",title:"Curvature of a curve",number:"26"}),a.createElement("p",null,"Imagine we have two curves, and we want to line them in up in a way that \"looks right\". What would we use as metric to let a computer decide what \"looks right\" means? For instance, we can start by ensuring that the two curves share an end coordinate, so that there is no \"gap\" between leaving one curve and entering the next, but that won't guarantee that things look right: both curves can be going in wildly different directions, and the resulting joined geometry will have a corner in it, rather than a smooth transition from one curve to the next. What we want is to ensure that the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Curvature"},a.createElement("em",null,"curvature"))," at the transition from one curve to the next \"looks good\". So, we could have them share an end coordinate, and then ensure that the derivatives for both curves match at that coordinate, and at a casual glance, that seems the perfect solution: if we make the derivatives match, then both the \"direction\" in which we travel from one curve to the next is the same, and the \"speed\" at which we travel the curve will be the same."),a.createElement("p",null,"Problem solved!"),a.createElement("p",null,"But, if we think about this a little more, this cannot possible work, because of something that you may have noticed in the section on ",a.createElement("a",{href:"#reordering"},"reordering curves"),": what a curve looks like, and the function that draws that curve, are not in some kind of universal, fixed, one-to-one relation. If we have some quadratic curve, then simply by raising the curve order we can get corresponding cubic, quartic, and higher and higher mathematical expressions that all draw the ",a.createElement("em",null,"exact same curve")," but with wildly different derivatives. So: if we want to make a transition from one curve to the next look good, and we want to use the derivative, then we suddenly need to answer the question: \"Which derivative?\"."),a.createElement("p",null,"How would you even decide? What makes the cubic derivatives better or less suited than, say, quintic derivatives? Wouldn't it be nicer if we could use something that was inherent to the curve, without being tied to the functions that yield that curve? And (of course) as it turns out, there is a way to define curvature in such a way that it only relies on what the curve actually looks like, and given where this section is in the larger body of this Primer, it should hopefully not be surprising that we thing we can use to define curvature is the thing we talked about in the previous section: arc length."),a.createElement("p",null,"Intuitively, this should make sense, even if we have no idea what the maths would look like: if we travel some fixed distance along some curve, then the point at that distance is simply the point at that distance. It doesn't matter what function we used to draw the curve: once we know what the curve looks like, the function(s) used to draw it become irrelevant: a point a third along the full distance of the curve is simply the point a third along the distance of the curve."),a.createElement("p",null,"You might think that in order to find the curvature of a curve, we now need to find and then solve the arc length function, and that would be a problem because we just saw that there is no way to actually do that: don't worry, we don't. We do need to know the ",a.createElement("em",null,"form")," of the arc length function, which we saw above, but it's not the thing we're actually interested in, and we're going to be rewriting it in a way that makes most of the crazy complex things about it just... disappear."),a.createElement("p",null,"In fact, after ",a.createElement("a",{href:"http://mathworld.wolfram.com/Curvature.html"},"running through the steps necessary")," to determine what we're left with if we use the arclength function's derivative (with another run-through of the maths ",a.createElement("a",{href:"https://math.stackexchange.com/a/275324/71940"},"here"),"), rather than the curve's original function's derivative, then the integral disappears entirely (because of the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus"},"fundamental therem of calculus"),"), and we're left with some surprisingly simple maths that relates curvature (denoted as \u03BA, \"kappa\") to\u2014and this is the truly surprising bit\u2014a specific combination of derivatives of our original function."),a.createElement("p",null,"Let me just highlight that before we move on: we calculate the curvature of a curve using the arc length function derivative, because the original function's derivative is entirely unreliable, and in doing so we end up with a formula that expresses curvature in terms of the original function's derivatives."),a.createElement("p",null,a.createElement("em",null,"That's crazy!")),a.createElement("p",null,"But, that's what makes maths such an interesting thing: it can show you that all your assumptions are completely wrong, only to then go \"but actually, you were on the right track all along, here: ...\" with a solution that is so easy to work with as to almost seem mundane. So: enough of all this text, how do we calculate curvature? What is the function for \u03BA? Concisely, the function is this:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/4061c0e23e37f144caa0f4f64bf130af84a6e322.svg",width:"118.99999999999999",height:"49"}),a.createElement("p",null,"Which is really just a \"short form\" that glosses over the fact that we're dealing with functions:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/e5e53f8be6f299f452175aa08a9ea14a0da90285.svg",width:"250.6",height:"57.4"}),a.createElement("p",null,"And while that's a litte more verbose, it's still just as simple to work with as the first function: the curvature at some point on any (and this cannot be overstated: ",a.createElement("em",null,"any"),") curve is a ratio between the first and second derivative cross product, and something that looks oddly similar to the standard Euclidean distance function. And nothing in these functions is hard to calculate either: for B\xE9zier curves, simply knowing our curve coordinates means ",a.createElement("a",{href:"#derivatives"},"we know what the first and second derivatives are"),", and so evaluating this function for any ",a.createElement("strong",null,"t")," value is just a matter of basic arithematics."),a.createElement("div",{className:"howtocode"},a.createElement("h3",{id:"implement-the-kappa-function"},"Implement the kappa function"),a.createElement("p",null,"In fact, let's just implement it right now:"),a.createElement("pre",null,"function kappa(t, B):\n d = B.getDerivative()\n dd = d.getDerivative()\n dx = d.getX(t)\n dy = d.getY(t)\n ddx = dd.getX(t)\n ddy = dd.getY(t)\n numerator = dx * ddy - ddx * dy\n denominator = pow(dx*dx + dy*dy, 1.5)\n return numerator / denominator\n"),a.createElement("p",null,"That was easy!"),a.createElement("p",null,"In fact, it stays easy because we can also compute the associated \"radius of curvature\", which gives us the implicit circle that \"fits\" the curve's curvature at any point, using what is possibly the simplest relation in this entire primer:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/030f65b17aa4cafabdd89042ac8093106da82a42.svg",width:"85.39999999999999",height:"39.199999999999996"}),a.createElement("p",null,"So that's a rather convenient fact to know, too.")),a.createElement("p",null,"So with all of that covered, let's line up some curves! The following graphic gives you two curves that look identical, but use quadratic and cubic functions, respectively. As you can see, despite their derivatives being necessarily different, their curvature (thanks to being derived based on maths that \"ignores\" specific function derivative, and instead gives a formulat that smooths out any differences) is exactly the same. And because of that, we can put them together such that the point where they overlap has the same curvature for both curves, giving us the smoothest looking transition we could ask for."),a.createElement(i,{handler:e.props.handler,section:"curvature",title:"Matching curvatures for a quadratic and cubic B\xE9zier curve",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw"}),a.createElement("p",null,"One thing you may have noticed in this sketch is that sometimes the curvature looks fine, but seems to be pointing in the wrong direction, making it hard to line up the curves properly. In your code you typically solve this by matching absolute values, but that's not super easy to program visually... however, we ",a.createElement("em",null,"can")," just show the curvature on both sides of the curve, making lining things up a bit easier:"),a.createElement(i,{handler:e.props.handler,section:"curvature",title:"(Easier) curvature matching for a quadratic and cubic B\xE9zier curve",setup:e.setup,sname:"setup",draw:e.drawOmni,dname:"drawOmni"}))}},tracing:{locale:"en-GB",title:"Tracing a curve at fixed distance intervals",getContent:function(e){return a.createElement("section",{className:"tracing"},a.createElement(r,{name:"tracing",title:"Tracing a curve at fixed distance intervals",number:"27"}),a.createElement("p",null,"Say you want to draw a curve with a dashed line, rather than a solid line, or you want to move something along the curve at fixed distance intervals over time, like a train along a track, and you want to use B\xE9zier curves."),a.createElement("p",null,"Now you have a problem."),a.createElement("p",null,"The reason you have a problem is that B\xE9zier curves are parametric functions with non-linear behaviour, whereas moving a train along a track is about as close to a practical example of linear behaviour as you can get. The problem we're faced with is that we can't just pick ",a.createElement("em",null,"t")," values at some fixed interval and expect the B\xE9zier functions to generate points that are spaced a fixed distance apart. In fact, let's look at the relation between \"distance long a curve\" and \"",a.createElement("em",null,"t")," value\", by plotting them against one another."),a.createElement("p",null,"The following graphic shows a particularly illustrative curve, and it's length-to-t plot. For linear traversal, this line needs to be straight, running from (0,0) to (length,1). This is, it's safe to say, not what we'll see, we'll see something wobbly instead. To make matters even worse, the length-to-",a.createElement("em",null,"t")," function is also of a much higher order than our curve is: while the curve we're using for this exercise is a cubic curve, which can switch concave/convex form once at best, the plot shows that the distance function along the curve is able to switch forms three times (to see this, try creating an S curve with the start/end close together, but the control points far apart)."),a.createElement(i,{handler:e.props.handler,section:"tracing",title:"The t-for-distance function",setup:e.setup,sname:"setup",draw:e.plotOnly,dname:"plotOnly"}),a.createElement("p",null,"We see a function that might be invertible, but we won't be able to do so, symbolically. You may remember from the section on arc length that we cannot actually compute the true arc length function as an expression of ",a.createElement("em",null,"t"),", which means we also can't compute the true inverted function that gives ",a.createElement("em",null,"t")," as an expression of length. So how do we fix this?"),a.createElement("p",null,"One way is to do what the graphic does: simply run through the curve, determine its ",a.createElement("em",null,"t"),"-for-length values as a set of discrete values at some high resolution (the graphic uses 100 discrete points), and then use those as a basis for finding an appropriate ",a.createElement("em",null,"t")," value, given a distance along the curve. This works quite well, actually, and is fairly fast."),a.createElement("p",null,"We can use some colour to show the difference between distance-based and time based intervals: the following graph is similar to the previous one, except it segments the curve in terms of equal-distance intervals. This shows as regular colour intervals going down the graph, but the mapping to ",a.createElement("em",null,"t")," values is not linear, so there will be (highly) irregular intervals along the horizontal axis. It also shows the curve in an alternating colouring based on the t-for-distance values we find our LUT:"),a.createElement(i,{handler:e.props.handler,section:"tracing",title:"Fixed-interval coloring a curve",setup:e.setup,sname:"setup",draw:e.drawColoured,dname:"drawColoured",onKeyDown:e.props.onKeyDown}),a.createElement("p",null,"Use your up and down arrow keys to increase or decrease the number of equidistant segments used to colour the curve."),a.createElement("p",null,"However, are there better ways? One such way is discussed in \"",a.createElement("a",{href:"http://www.geometrictools.com/Documentation/MovingAlongCurveSpecifiedSpeed.pdf"},"Moving Along a Curve with Specified Speed"),"\" by David Eberly of Geometric Tools, LLC, but basically because we have no explicit length function (or rather, one we don't have to constantly compute for different intervals), you may simply be better off with a traditional lookup table (LUT)."))}},intersections:{locale:"en-GB",title:"Intersections",getContent:function(e){return a.createElement("section",{className:"intersections"},a.createElement(r,{name:"intersections",title:"Intersections",number:"28"}),a.createElement("p",null,"Let's look at some more things we will want to do with B\xE9zier curves. Almost immediately after figuring out how to get bounding boxes to work, people tend to run into the problem that even though the minimal bounding box (based on rotation) is tight, it's not sufficient to perform true collision detection. It's a good first step to make sure there ",a.createElement("em",null,"might")," be a collision (if there is no bounding box overlap, there can't be one), but in order to do real collision detection we need to know whether or not there's an intersection on the actual curve."),a.createElement("p",null,"We'll do this in steps, because it's a bit of a journey to get to curve/curve intersection checking. First, let's start simple, by implementing a line-line intersection checker. While we can solve this the traditional calculus way (determine the functions for both lines, then compute the intersection by equating them and solving for two unknowns), linear algebra actually offers a nicer solution."),a.createElement("h3",{id:"line-line-intersections"},"Line-line intersections"),a.createElement("p",null,"If we have two line segments with two coordinates each, segments A-B and C-D, we can find the intersection of the lines these segments are an intervals on by linear algebra, using the procedure outlined in this ",a.createElement("a",{href:"http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2#line_line_intersection"},"top coder")," article. Of course, we need to make sure that the intersection isn't just on the lines our line segments lie on, but actually on our line segments themselves. So after we find the intersection, we need to verify that it lies without the bounds of our original line segments."),a.createElement("p",null,"The following graphic implements this intersection detection, showing a red point for an intersection on the lines our segments lie on (thus being a virtual intersection point), and a green point for an intersection that lies on both segments (being a real intersection point)."),a.createElement(i,{handler:e.props.handler,section:"intersections",title:"Line/line intersections",setup:e.setupLines,sname:"setupLines",draw:e.drawLineIntersection,dname:"drawLineIntersection"}),a.createElement("div",{className:"howtocode"},a.createElement("h3",{id:"implementing-line-line-intersections"},"Implementing line-line intersections"),a.createElement("p",null,"Let's have a look at how to implement a line-line intersection checking function. The basics are covered in the article mentioned above, but sometimes you need more function signatures, because you might not want to call your function with eight distinct parameters. Maybe you're using point structs for the line. Let's get coding:"),a.createElement("pre",null,"lli8 = function(x1,y1,x2,y2,x3,y3,x4,y4):\n var nx=(x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4),\n ny=(x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4),\n d=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);\n if d=0:\n return false\n return point(nx/d, ny/d)\n\nlli4 = function(p1, p2, p3, p4):\n var x1 = p1.x, y1 = p1.y,\n x2 = p2.x, y2 = p2.y,\n x3 = p3.x, y3 = p3.y,\n x4 = p4.x, y4 = p4.y;\n return lli8(x1,y1,x2,y2,x3,y3,x4,y4)\n\nlli = function(line1, line2):\n return lli4(line1.p1, line1.p2, line2.p1, line2.p2)\n")),a.createElement("h3",{id:"what-about-curve-line-intersections-"},"What about curve-line intersections?"),a.createElement("p",null,"Curve/line intersection is more work, but we've already seen the techniques we need to use in order to perform it: first we translate/rotate both the line and curve together, in such a way that the line coincides with the x-axis. This will position the curve in a way that makes it cross the line at points where its y-function is zero. By doing this, the problem of finding intersections between a curve and a line has now become the problem of performing root finding on our translated/rotated curve, as we already covered in the section on finding extremities."),a.createElement(i,{handler:e.props.handler,section:"intersections",title:"Quadratic curve/line intersections",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"intersections",title:"Cubic curve/line intersections",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}),a.createElement("p",null,"Curve/curve intersection, however, is more complicated. Since we have no straight line to align to, we can't simply align one of the curves and be left with a simple procedure. Instead, we'll need to apply two techniques we've met before: de Casteljau's algorithm, and curve splitting."))}},curveintersection:{locale:"en-GB",title:"Curve/curve intersection",getContent:function(e){return a.createElement("section",{className:"curveintersection"},a.createElement(r,{name:"curveintersection",title:"Curve/curve intersection",number:"29"}),a.createElement("p",null,"Using de Casteljau's algorithm to split the curve we can now implement curve/curve intersection finding using a \"divide and conquer\" technique:"),a.createElement("ul",null,a.createElement("li",null,"Take two curves ",a.createElement("em",null,"C",a.createElement("sub",null,"1"))," and ",a.createElement("em",null,"C",a.createElement("sub",null,"2")),", and treat them as a pair."),a.createElement("li",null,"If their bounding boxes overlap, split up each curve into two sub-curves"),a.createElement("li",null,"With ",a.createElement("em",null,"C",a.createElement("sub",null,"1.1")),", ",a.createElement("em",null,"C",a.createElement("sub",null,"1.2")),", ",a.createElement("em",null,"C",a.createElement("sub",null,"2.1"))," and ",a.createElement("em",null,"C",a.createElement("sub",null,"2.2")),", form four new pairs (",a.createElement("em",null,"C",a.createElement("sub",null,"1.1")),",",a.createElement("em",null,"C",a.createElement("sub",null,"2.1")),"), (",a.createElement("em",null,"C",a.createElement("sub",null,"1.1")),", ",a.createElement("em",null,"C",a.createElement("sub",null,"2.2")),"), (",a.createElement("em",null,"C",a.createElement("sub",null,"1.2")),",",a.createElement("em",null,"C",a.createElement("sub",null,"2.1")),"), and (",a.createElement("em",null,"C",a.createElement("sub",null,"1.2")),",",a.createElement("em",null,"C",a.createElement("sub",null,"2.2")),")."),a.createElement("li",null,"For each pair, check whether their bounding boxes overlap.",a.createElement("ul",null,a.createElement("li",null,"If their bounding boxes do not overlap, discard the pair, as there is no intersection between this pair of curves."),a.createElement("li",null,"If there ",a.createElement("em",null,"is")," overlap, rerun all steps for this pair."))),a.createElement("li",null,"Once the sub-curves we form are so small that they effectively occupy sub-pixel areas, we consider an intersection found, noting that we might have a cluster of multiple intersections at the sub-pixel level, out of which we pick one to act as \"found\" ",a.createElement("code",null,"t")," value (we can either throw all but one away, we can average the cluster's ",a.createElement("code",null,"t")," values, or you can do something even more creative).")),a.createElement("p",null,"This algorithm will start with a single pair, \"balloon\" until it runs in parallel for a large number of potential sub-pairs, and then taper back down as it homes in on intersection coordinates, ending up with as many pairs as there are intersections."),a.createElement("p",null,"The following graphic applies this algorithm to a pair of cubic curves, one step at a time, so you can see the algorithm in action. Click the button to run a single step in the algorithm, after setting up your curves in some creative arrangement. The algorithm resets once it's found a solution, so you can try this with lots of different curves (can you find the configuration that yields the maximum number of intersections between two cubic curves? Nine intersections!)"),a.createElement(i,{handler:e.props.handler,section:"curveintersection",title:"Curve/curve intersections",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw"},a.createElement("button",{onClick:e.stepUp},"advance one step")),a.createElement("p",null,"Self-intersection is dealt with in the same way, except we turn a curve into two or more curves first based on the inflection points. We then form all possible curve pairs with the resultant segments, and run exactly the same algorithm. All non-overlapping curve pairs will be removed after the first iteration, and the remaining steps home in on the curve's self-intersection points."))}},abc:{locale:"en-GB",title:"The projection identity",getContent:function(e){return a.createElement("section",{className:"abc"},a.createElement(r,{name:"abc",title:"The projection identity",number:"30"}),a.createElement("p",null,"De Casteljau's algorithm is the pivotal algorithm when it comes to B\xE9zier curves. You can use it not just to split curves, but also to draw them efficiently (especially for high-order B\xE9zier curves), as well as to come up with curves based on three points and a tangent. Particularly this last thing is really useful because it lets us \"mould\" a curve, by picking it up at some point, and dragging that point around to change the curve's shape."),a.createElement("p",null,"How does that work? Succinctly: we run de Casteljau's algorithm in reverse!"),a.createElement("p",null,"In order to run de Casteljau's algorithm in reverse, we need a few basic things: a start and end point, a point on the curve that want to be moving around, which has an associated ",a.createElement("em",null,"t")," value, and a point we've not explicitly talked about before, and as far as I know has no explicit name, but lives one iteration higher in the de Casteljau process then our on-curve point does. I like to call it \"A\" for reasons that will become obvious."),a.createElement("p",null,"So let's use graphics instead of text to see where this \"A\" is, because text only gets us so far: in the following graphic, click anywhere on the curves to see the identity information that we'll be using to run de Casteljau in reverse (you can manipulate the curve even after picking a point. Note the \"ratio\" value when you do so: does it change?):"),a.createElement("div",{className:"figure"},a.createElement(i,{handler:e.props.handler,section:"abc",inline:!0,title:"Projections in a quadratic B\xE9zier curve",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onClick:e.onClick}),a.createElement(i,{handler:e.props.handler,section:"abc",inline:!0,title:"Projections in a cubic B\xE9zier curve",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onClick:e.onClick})),a.createElement("p",null,"Clicking anywhere on the curves shows us three things:"),a.createElement("ol",null,a.createElement("li",null,"our on-curve point; let's call that ",a.createElement("b",null,"B"),","),a.createElement("li",null,"a point at the tip of B's \"hat\", on de Casteljau step up; let's call that ",a.createElement("b",null,"A"),", and"),a.createElement("li",null,"a point that we get by projecting B onto the start--end baseline; let's call that ",a.createElement("b",null,"C"),".")),a.createElement("p",null,"These three values A, B, and C hide an important identity formula for quadratic and cubic B\xE9zier curves: for any point on the curve with some ",a.createElement("em",null,"t")," value, the ratio distance of C along the baseline is fixed: if some ",a.createElement("em",null,"t")," value sets up a C that is 20% away from the start and 80% away from the end, then it doesn't matter where the start, end, or control points are; for that ",a.createElement("em",null,"t")," value, C will ",a.createElement("em",null,"always")," lie at 20% from the start and 80% from the end point. Go ahead, pick an on-curve point in either graphic and then move all the other points around: if you only move the control points, start and end won't move, and so neither will C, and if you move either start or end point, C will move but its relative position will not change. The following function stays true:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f48f095d9c37c079ff6a5f71b3047397aa7dfc6b.svg",width:"207.2",height:"16.799999999999997"}),a.createElement("p",null,"So that just leaves finding A."),a.createElement("div",{className:"note"},a.createElement("p",null,"While that relation is fixed, the function ",a.createElement("em",null,"u(t)")," differs depending on whether we're working with quadratic or cubic curves:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/cb35e42bf53bfc2b96f959e78256da01f8b91dbc.svg",width:"207.2",height:"91"}),a.createElement("p",null,"So, if we know the start and end coordinates, and we know the ",a.createElement("em",null,"t")," value, we know C:"),a.createElement("div",{className:"figure"},a.createElement(i,{handler:e.props.handler,section:"abc",inline:!0,title:"Quadratic value of C for t",draw:e.drawQCT,dname:"drawQCT",onMouseMove:e.setCT}),a.createElement(i,{handler:e.props.handler,section:"abc",inline:!0,title:"Cubic value of C for t",draw:e.drawCCT,dname:"drawCCT",onMouseMove:e.setCT})),a.createElement("p",null,"Mouse-over the graphs to see the expression for C, given the ",a.createElement("em",null,"t")," value at the mouse pointer.")),a.createElement("p",null,"There's also another important bit of information that is inherent to the ABC values: while the distances between A and B, and B and C, are dynamic (based on where we put B), the ",a.createElement("em",null,"ratio")," between the two distances is stable. Given some ",a.createElement("em",null,"t")," value, the following always holds:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/6cb3e94fe9164128a25570a32abed15baa726f17.svg",width:"263.2",height:"40.599999999999994"}),a.createElement("p",null,"This leads to a pretty powerful bit of knowledge: merely by knowing the ",a.createElement("em",null,"t")," value of some on curve point, we know where C has to be (as per the above note), and because we know B and C, and thus have the distance between them, we know where A has to be:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/1dffb79b42799c95c899e689b074361f662ec807.svg",width:"228.2",height:"39.199999999999996"}),a.createElement("p",null,"And that's it, all values found."),a.createElement("div",{className:"note"},a.createElement("p",null,"Much like the ",a.createElement("em",null,"u(t)")," function in the above note, the ",a.createElement("em",null,"ratio(t)")," function depends on whether we're looking at quadratic or cubic curves. Their form is intrinsically related to the ",a.createElement("em",null,"u(t)")," function in that they both come rolling out of the same function evaluation, explained over on ",a.createElement("a",{href:"http://mathoverflow.net/questions/122257/finding-the-formula-for-B\xE9zier-curve-ratios-hull-point-point-baseline"},"MathOverflow")," by Boris Zbarsky and myself. The ratio functions are the \"s(t)\" functions from the answers there, while the \"u(t)\" functions have the same name both here and on MathOverflow."),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/7ef64890f95db9e48258edb46a3d52d5ed143155.svg",width:"257.59999999999997",height:"43.4"}),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5f2bb71795c615637d632da70b722938cb103b03.svg",width:"233.79999999999998",height:"43.4"}),a.createElement("p",null,"Unfortunately, this trick only works for quadratic and cubic curves. Once we hit higher order curves, things become a lot less predictable; the \"fixed point ",a.createElement("em",null,"C"),"\" is no longer fixed, moving around as we move the control points, and projections of ",a.createElement("em",null,"B")," onto the line between start and end may actually lie on that line before the start, or after the end, and there are no simple ratios that we can exploit.")),a.createElement("p",null,"So: if we know B and its corresponding ",a.createElement("em",null,"t")," value, then we know all the ABC values, which \u2014together with a start and end coordinate\u2014 gives us the necessary information to reconstruct a curve's \"de Casteljau skeleton\", which means that two points and a value between 0 and 1, we can come up with a curve. And that opens up possibilities: curve manipulation by dragging an on-curve point, as well as curve fitting of \"a bunch of coordinates\". These are useful things, and we'll look at both in the next sections."))}},moulding:{locale:"en-GB",title:"Manipulating a curve",getContent:function(e){return a.createElement("section",{className:"moulding"},a.createElement(r,{name:"moulding",title:"Manipulating a curve",number:"31"}),a.createElement("p",null,"Armed with knowledge of the \"ABC\" relation, we can now update a curve interactively, by letting people click anywhere on the curve, find the ",a.createElement("em",null,"t"),"-value matching that coordinate, and then letting them drag that point around. With every drag update we'll have a new point \"B\", which we can combine with the fixed point \"C\" to find our new point A. Once we have those, we can reconstruct the de Casteljau skeleton and thus construct a new curve with the same start/end points as the original curve, passing through the user-selected point B, with correct new control points."),a.createElement(i,{handler:e.props.handler,section:"moulding",title:"Moulding a quadratic B\xE9zier curve",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.drawMould,dname:"drawMould",onClick:e.placeMouldPoint,onMouseDown:e.markQB,onMouseDrag:e.dragQB,onMouseUp:e.saveCurve}),a.createElement("p",null,a.createElement("strong",null,"Click-dragging the curve itself")," shows what we're using to compute the new coordinates: while dragging you will see the original point B and its corresponding ",a.createElement("i",null,"t"),"-value, the original point C for that ",a.createElement("i",null,"t"),"-value, as well as the new point B' based on the mouse cursor. Since we know the ",a.createElement("i",null,"t"),"-value for this configuration, we can compute the ABC ratio for this configuration, and we know that our new point A' should like at a distance:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5d818e55ada5ac32c97637a3b608b660f4a94adb.svg",width:"232.39999999999998",height:"37.8"}),a.createElement("p",null,"For quadratic curves, this means we're done, since the new point A' is equivalent to the new quadratic control point. For cubic curves, we need to do a little more work:"),a.createElement(i,{handler:e.props.handler,section:"moulding",title:"Moulding a cubic B\xE9zier curve",setup:e.setupCubic,sname:"setupCubic",draw:e.drawMould,dname:"drawMould",onClick:e.placeMouldPoint,onMouseDown:e.markCB,onMouseDrag:e.dragCB,onMouseUp:e.saveCurve}),a.createElement("p",null,"To help understand what's going on, the cubic graphic shows the full de Casteljau construction \"hull\" when repositioning point B. We compute A' in exactly the same way as before, but we also record the final strut line that forms B in the original curve. Given A', B', and the endpoints e1 and e2 of the strut line relative to B', we can now compute where the new control points should be. Remember that B' lies on line e1--e2 at a distance ",a.createElement("i",null,"t"),", because that's how B\xE9zier curves work. In the same manner, we know the distance A--e1 is only line-interval [0,t] of the full segment, and A--e2 is only line-interval [t,1], so constructing the new control points is fairly easy."),a.createElement("p",null,"First, we construct the one-level-of-de-Casteljau-up points:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/9bc530c9563297ad5d8bf574beb1b4f2732de75c.svg",width:"138.6",height:"78.39999999999999"}),a.createElement("p",null,"And then we can compute the new control points:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d53cad094fddaacbb047c9d7c465a5011e3bfbfd.svg",width:"163.79999999999998",height:"78.39999999999999"}),a.createElement("p",null,"And that's cubic curve manipulation."))}},pointcurves:{locale:"en-GB",title:"Creating a curve from three points",getContent:function(e){return a.createElement("section",{className:"pointcurves"},a.createElement(r,{name:"pointcurves",title:"Creating a curve from three points",number:"32"}),a.createElement("p",null,"Given the preceding section on curve manipulation, we can also generate quadratic and cubic curves from any three points. However, unlike circle-fitting, which requires just three points, B\xE9zier curve fitting requires three points, as well as a ",a.createElement("em",null,"t")," value, so we can figure out where point 'C' needs to be."),a.createElement("p",null,"The following graphic lets you place three points, and will use the preceding sections on the ABC ratio and curve construction to form a quadratic curve through them. You can move the points you've placed around by click-dragging, or try a new curve by drawing new points with pure clicks. (There's some freedom here, so for illustrative purposes we clamped ",a.createElement("em",null,"t")," to simply be 0.5, lets us bypass some maths, since a ",a.createElement("em",null,"t")," value of 0.5 always puts C in the middle of the start--end line segment)"),a.createElement(i,{handler:e.props.handler,section:"pointcurves",title:"Fitting a quadratic B\xE9zier curve",setup:e.setup,sname:"setup",draw:e.drawQuadratic,dname:"drawQuadratic",onClick:e.onClick}),a.createElement("p",null,"For cubic curves we also need some values to construct the \"de Casteljau line through B\" with, and that gives us quite a bit of choice. Since we've clamped ",a.createElement("em",null,"t")," to 0.5, we'll set up a line through B parallel to the line start--end, with a length that is proportional to the length of the line B--C: the further away from the baseline B is, the wider its construction line will be, and so the more \"bulby\" the curve will look. This still gives us some freedom in terms of exactly how to scale the length of the construction line as we move B closer or further away from the baseline, so I simply picked some values that sort-of-kind-of look right in that if a circle through (start,B,end) forms a perfect hemisphere, the cubic curve constructed forms something close to a hemisphere, too, and if the points lie on a line, then the curve constructed has the control points very close to B, while still lying between B and the correct curve end point:"),a.createElement(i,{handler:e.props.handler,section:"pointcurves",title:"Fitting a cubic B\xE9zier curve",setup:e.setup,sname:"setup",draw:e.drawCubic,dname:"drawCubic",onClick:e.onClick}),a.createElement("p",null,"In each graphic, the blue parts are the values that we \"just have\" simply by setting up our three points, combined with our decision on which ",a.createElement("em",null,"t")," value to use (and construction line orientation and length for cubic curves). There are of course many ways to determine a combination of ",a.createElement("em",null,"t")," and tangent values that lead to a more \"\xE6sthetic\" curve, but this will be left as an exercise to the reader, since there are many, and \xE6sthetics are often quite personal."))}},curvefitting:{locale:"en-GB",title:"Curve fitting",getContent:function(e){return a.createElement("section",{className:"curvefitting"},a.createElement(r,{name:"curvefitting",title:"Curve fitting",number:"33"}),a.createElement("p",null,"Given the previous section, one question you might have is \"what if I don't want to guess ",a.createElement("code",null,"t")," values?\". After all, plenty of graphics packages do automated curve fitting, so how can we implement that in a way that just finds us reasonable ",a.createElement("code",null,"t")," values all on its own?"),a.createElement("p",null,"And really this is just a variation on the question \"how do I get the curve through these X points?\", so let's look at that. Specifically, let's look at the answer: \"curve fitting\". This is in fact a rather rich field in geometry, applying to anything from data modelling to path abstraction to \"drawing\", so there's a fair number of ways to do curve fitting, but we'll look at one of the most common approaches: something called a ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Least_squares"},"least squares")," ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Polynomial_regression"},"polynomial regression"),". In this approach, we look at the number of points we have in our data set, roughly determine what would be an appropriate order for a curve that would fit these points, and then tackle the question \"given that we want an ",a.createElement("code",null,"nth")," order curve, what are the coordinates we can find such that our curve is \"off\" by the least amount?\"."),a.createElement("p",null,"Now, there are many ways to determine how \"off\" points are from the curve, which is where that \"least squares\" term comes in. The most common tool in the toolbox is to minimise the ",a.createElement("em",null,"squared distance")," between each point we have, and the corresponding point on the curve we end up \"inventing\". A curve with a snug fit will have zero distance between those two, and a bad fit will have non-zero distances between every such pair. It's a workable metric. You might wonder why we'd need to square, rather than just ensure that distance is a positive value (so that the total error is easy to compute by just summing distances) and the answer really is \"because it tends to be a little better\". There's lots of literature on the web if you want to deep-dive the specific merits of least squared error metrics versus least absolute error metrics, but those are ",a.createElement("em",null,"well")," beyond the scope of this material."),a.createElement("p",null,"So let's look at what we end up with in terms of curve fitting if we start with the idea of performing least squares B\xE9zier fitting. We're going to follow a procedure similar to the one described by Jim Herold over on his ",a.createElement("a",{href:"https://web.archive.org/web/20180403213813/http://jimherold.com/2012/04/20/least-squares-bezier-fit/"},"\"Least Squares B\xE9zier Fit\"")," article, and end with some nice interactive graphics for doing some curve fitting."),a.createElement("p",null,"Before we begin, we're going to use the curve in matrix form. In the ",a.createElement("a",{href:"#matrix"},"section on matrices"),", I mentioned that some things are easier if we use the matrix representation of a B\xE9zier curve rather than its calculus form, and this is one of those things."),a.createElement("p",null,"As such, the first step in the process is expressing our B\xE9zier curve as powers/coefficients/coordinate matrix ",a.createElement("strong",null,"T x M x C"),", by expanding the B\xE9zier functions."),a.createElement("div",{className:"note"},a.createElement("h2",{id:"revisiting-the-matrix-representation"},"Revisiting the matrix representation"),a.createElement("p",null,"Rewriting B\xE9zier functions to matrix form is fairly easy, if you first expand the function, and then arrange them into a multiple line form, where each line corresponds to a power of t, and each column is for a specific coefficient. First, we expand the function:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/82f4b5b4a4ced5aca7032559712f78b8698bd535.svg",width:"309.4",height:"44.8"}),a.createElement("p",null,"And then we (trivially) rearrange the terms across multiple lines:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c8d84ef5ab015a90c428c005b27d5e49f8bfb54a.svg",width:"226.79999999999998",height:"67.19999999999999"}),a.createElement("p",null,"This rearrangement has \"factors of t\" at each row (the first row is t\u2070, i.e. \"1\", the second row is t\xB9, i.e. \"t\", the third row is t\xB2) and \"coefficient\" at each column (the first column is all terms involving \"a\", the second all terms involving \"b\", the third all terms involving \"c\")."),a.createElement("p",null,"With that arrangement, we can easily decompose this as a matrix multiplication:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/9cf60881f3f137f8ca3053b0b42ee1dc86c172b3.svg",width:"600.5999999999999",height:"56"}),a.createElement("p",null,"We can do the same for the cubic curve, of course. We know the base function for cubics:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/6a78e1698672314533d60a928083231303f6d93b.svg",width:"372.4",height:"19.599999999999998"}),a.createElement("p",null,"So we write out the expansion and rearrange:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/3dc2b59facbec226f6ca40d7236e5f0a2d338f5d.svg",width:"260.4",height:"91"}),a.createElement("p",null,"Which we can then decompose:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/726e708e206906f6457b0ca27012a2dc1fe05c35.svg",width:"424.2",height:"75.6"}),a.createElement("p",null,"And, of course, we can do this for quartic curves too (skipping the expansion step):"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/13c3dd93dd8c3fc3375aec5950ed7def3a6bb0ef.svg",width:"515.1999999999999",height:"96.6"}),a.createElement("p",null,"And so and on so on. Now, let's see how to use these ",a.createElement("strong",null,"T"),", ",a.createElement("strong",null,"M"),", and ",a.createElement("strong",null,"C"),", to do some curve fitting.")),a.createElement("p",null,"Let's get started: we're going to assume we picked the right order curve: for ",a.createElement("code",null,"n")," points we're fitting an ",a.createElement("code",null,"n-1"),a.createElement("sup",null,"th")," order curve, so we \"start\" with a vector ",a.createElement("strong",null,"P")," that represents the coordinates we already know, and for which we want to do curve fitting:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ff2baff5722084423f744690db1cedd1b9e5f60b.svg",width:"65.8",height:"77"}),a.createElement("p",null,"Next, we need to figure out appropriate ",a.createElement("code",null,"t")," values for each point in the curve, because we need something that lets us tie \"the actual coordinate\" to \"some point on the curve\". There's a fair number of different ways to do this (and a large part of optimizing \"the perfect fit\" is about picking appropriate ",a.createElement("code",null,"t")," values), but in this case let's look at two \"obvious\" choices:"),a.createElement("ol",null,a.createElement("li",null,"equally spaced ",a.createElement("code",null,"t")," values, and"),a.createElement("li",null,a.createElement("code",null,"t")," values that align with distance along the polygon.")),a.createElement("p",null,"The first one is really simple: if we have ",a.createElement("code",null,"n")," points, then we'll just assign each point ",a.createElement("code",null,"i")," a ",a.createElement("code",null,"t")," value of ",a.createElement("code",null,"(i-1)/(n-1)"),". So if we have four points, the first point will have ",a.createElement("code",null,"t=(1-1)/(4-1)=0/3"),", the second point will have ",a.createElement("code",null,"t=(2-1)/(4-1)=1/3"),", the third point will have ",a.createElement("code",null,"t=2/3"),", and the last point will be ",a.createElement("code",null,"t=1"),". We're just straight up spacing the ",a.createElement("code",null,"t")," values to match the number of points we have."),a.createElement("p",null,"The second one is a little more interesting: since we're doing polynomial regression, we might as well exploit the fact that our base coordinates just constitute a collection of line segments. At the first point, we're fixing t=0, and the last point, we want t=1, and anywhere in between we're simply going to say that ",a.createElement("code",null,"t")," is equal to the distance along the polygon, scaled to the [0,1] domain."),a.createElement("p",null,"To get these values, we first compute the general \"distance along the polygon\" matrix:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2b965d26ec8d62894031736a9718fa6145be6df4.svg",width:"414.4",height:"42"}),a.createElement("p",null,"Where ",a.createElement("code",null,"length()")," is literally just that: the length of the line segment between the point we're looking at, and the previous point. This isn't quite enough, of course: we still need to make sure that all the values between ",a.createElement("code",null,"i=1")," and ",a.createElement("code",null,"i=n")," fall in the [0,1] interval, so we need to scale all values down by whatever the total length of the polygon is:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/565dc8e6ecf61a2d922595936452c3b460814bc7.svg",width:"285.59999999999997",height:"57.4"}),a.createElement("p",null,"And now we can move on to the actual \"curve fitting\" part: what we want is a function that lets us compute \"ideal\" control point values such that if we build a B\xE9zier curve with them, that curve passes through all our original points. Or, failing that, have an overall error distance that is as close to zero as we can get it. So, let's write out what the error distance looks like."),a.createElement("p",null,"As mentioned before, this function is really just \"the distance between the actual coordinate, and the coordinate that the curve evaluates to for the associated ",a.createElement("code",null,"t")," value\", which we'll square to get rid of any pesky negative signs:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f9a3b359cace9e3e863e45b3910046e3e9fc9901.svg",width:"186.2",height:"23.799999999999997"}),a.createElement("p",null,"Since this function only deals with individual coordinates, we'll need to sum over all coordinates in order to get the full error function. So, we literally just do that; the total error function is simply the sum of all these individual errors:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f9570f3039f307765257306430c9d775c375c84d.svg",width:"204.39999999999998",height:"43.4"}),a.createElement("p",null,"And here's the trick that justifies using matrices: while we can work with individual values using calculus, with matrices we can compute as many values as we make our matrices big, all at the \"same time\", We can replace the individual terms p",a.createElement("sub",null,"i")," with the full ",a.createElement("strong",null,"P")," coordinate matrix, and we can replace B\xE9zier(s",a.createElement("sub",null,"i"),") with the matrix representation ",a.createElement("strong",null,"T x M x C")," we talked about before, which gives us:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/25a84d68a97ef2dcc8249a91db2165ffcf79dbb6.svg",width:"148.39999999999998",height:"22.4"}),a.createElement("p",null,"In which we can replace the rather cumbersome \"squaring\" operation with a more conventional matrix equivalent:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c42c1c0a8ca170344271b444747cfd9a8612b35e.svg",width:"236.6",height:"22.4"}),a.createElement("p",null,"Here, the letter ",a.createElement("code",null,"T")," is used instead of the number 2, to represent the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Transpose"},"matrix transpose"),"; each row in the original matrix becomes a column in the transposed matrix instead (row one becomes column one, row two becomes column two, and so on)."),a.createElement("p",null,"This leaves one problem: ",a.createElement("strong",null,"T")," isn't actually the matrix we want: we don't want symbolic ",a.createElement("code",null,"t")," values, we want the actual numerical values that we computed for ",a.createElement("strong",null,"S"),", so we need to form a new matrix, which we'll call \uD835\uDD4B, that makes use of those, and then use that \uD835\uDD4B instead of ",a.createElement("strong",null,"T")," in our error function:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2846a7b106ef541c1eef5cbd0c1975efe1a9ec6e.svg",width:"211.39999999999998",height:"100.8"}),a.createElement("p",null,"Which, because of the first and last values in ",a.createElement("strong",null,"S"),", means:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/93387a7b2b74cf58910f4bae2b36247f386603e0.svg",width:"222.6",height:"96.6"}),a.createElement("p",null,"Now we can properly write out the error function as matrix operations:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2399d92c96ffe4aaf0c205bd43d1cc5468876a33.svg",width:"242.2",height:"22.4"}),a.createElement("p",null,"So, we have our error function: we now need to figure out the expression for where that function has minimal value, e.g. where the error between the true coordinates and the coordinates generated by the curve fitting is smallest. Like in standard calculus, this requires taking the derivative, and determining where that derivative is zero:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/565ecfe60542cae04ff16bbe84ee8d0371daaa8b.svg",width:"207.2",height:"37.8"}),a.createElement("div",{className:"note"},a.createElement("h2",{id:"where-did-this-derivative-come-from-"},"Where did this derivative come from?"),a.createElement("p",null," That... is a good question. In fact, when trying to run through this approach, I ran into the same question! And you know what? I straight up had no idea. I'm decent enough at calculus, I'm decent enough at linear algebra, and I just don't know."),a.createElement("p",null," So I did what I always do when I don't understand something: I asked someone to help me understand how things work. In this specific case, I ",a.createElement("a",{href:"https://math.stackexchange.com/questions/2825438"},"posted a question")," to ",a.createElement("a",{href:"https://math.stackexchange.com"},"Math.stackexchange"),", and received a answer that goes into way more detail than I had hoped to receive."),a.createElement("p",null," Is that answer useful to you? Probably: no. At least, not unless you like understanding maths on a recreational level. And I do mean maths in general, not just basic algebra. But it does help in giving us a reference in case you ever wonder \"Hang on. Why was that true?\". There are answers. They might just require some time to come to understand.")),a.createElement("p",null,"Now, given the above derivative, we can rearrange the terms (following the rules of matrix algebra) so that we end up with an expression for ",a.createElement("strong",null,"C"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c80718dacd1cea3b7128d68819a460022f419ed6.svg",width:"176.39999999999998",height:"28"}),a.createElement("p",null,"Here, the \"to the power negative one\" is the notation for the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Invertible_matrix"},"matrix inverse"),". But that's all we have to do: we're done. Starting with ",a.createElement("strong",null,"P")," and inventing some ",a.createElement("code",null,"t")," values based on the polygon the coordinates in ",a.createElement("strong",null,"P")," define, we can compute the corresponding B\xE9zier coordinates ",a.createElement("strong",null,"C")," that specify a curve that goes through our points. Or, if it can't go through them exactly, as near as possible."),a.createElement("p",null,"So before we try that out, how much code is involved in implementing this? Honestly, that answer depends on how much you're going to be writing yourself. If you already have a matrix maths library available, then really not that much code at all. On the other hand, if you are writing this from scratch, you're going to have to write some utility functions for doing your matrix work for you, so it's really anywhere from 50 lines of code to maybe 200 lines of code. Not a bad price to pay for being able to fit curves to prespecified coordinates."),a.createElement("p",null,"So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bezier curve of the appropriate order. Four points? Cubic Bezier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once you hit 10",a.createElement("sup",null,"th")," or higher order curves. But it might not!"),a.createElement("div",{className:"figure"},a.createElement(i,{handler:e.props.handler,section:"curvefitting",title:"Fitting a B\xE9zier curve",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw",onClick:e.onClick},a.createElement("button",{onClick:e.toggle,style:"position:absolute; right: 0;"},"toggle"),a.createElement(l,{ref:function(t){return e.sliders=t},onChange:e.processTimeUpdate}))),a.createElement("p",null,"You'll note there is a convenient \"toggle\" buttons that lets you toggle between equidistance ",a.createElement("code",null,"t")," values, and distance ratio along the polygon. Arguably more interesting is that once you have points to abstract a curve, you also get ",a.createElement("em",null,"direct control")," over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is."))}},catmullconv:{locale:"en-GB",title:"B\xE9zier curves and Catmull-Rom curves",getContent:function(){return a.createElement("section",{className:"catmullconv"},a.createElement(r,{name:"catmullconv",title:"B\xE9zier curves and Catmull-Rom curves",number:"34"}),a.createElement("p",null,"Taking an excursion to different splines, the other common design curve is the ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull.E2.80.93Rom_spline"},"Catmull-Rom spline"),". Now, a Catmull-Rom spline is a form of ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Cubic_Hermite_spline"},"cubic Hermite spline"),", and as it so happens the cubic B\xE9zier curve is ",a.createElement("em",null,"also")," a cubic Hermite spline, so maybe... maybe we can convert one into the other, and back, with some simple substitutions?"),a.createElement("p",null,"Unlike B\xE9zier curves, Catmull-Rom splines pass through each point used to define the curve, except the first and last, which makes sense if you read the \"natural language\" description for how a Catmull-Rom spline works: a Catmull-Rom spline is a curve that, at each point P",a.createElement("sub",null,"x"),", has a tangent along the line P",a.createElement("sub",null,"x-1")," to P",a.createElement("sub",null,"x+1"),". The curve runs from points P",a.createElement("sub",null,"2")," to P",a.createElement("sub",null,"n-1"),", and has a \"tension\" that determines how fast the curve passes through each point. The lower the tension, the faster the curve goes through each point, and the bigger its local tangent is."),a.createElement("p",null,"I'll be showing the conversion to and from Catmull-Rom curves for the tension that the Processing language uses for its Catmull-Rom algorithm."),a.createElement("p",null,"We start with showing the Catmull-Rom matrix form, which looks similar to the B\xE9zier matrix form, with slightly different values in the matrix:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5fc1c44e623f2a9fbeefdaa204557479e3debf5a.svg",width:"429.79999999999995",height:"78.39999999999999"}),a.createElement("p",null,"However, there's something funny going on here: the coordinate column matrix looks weird. The reason is that Catmull-Rom curves are actually curve segments that are described by two coordinate points, and two tangents; the curve starts at coordinate V1, and ends at coordinate V2, with the curve \"departing\" V1 with a tangent vector V'1 and \"arriving\" at V2 with tangent vector V'2."),a.createElement("p",null,"This is not particularly useful if we want to draw Catmull-Rom curves in the same way we draw B\xE9zier curves, i.e. by providing four points. However, we can fairly easily go from the former to the latter, but it's going to require some linear algebra, so if you just want to know how to convert between the two coordinate systems: skip the following bit."),a.createElement("p",null,"But... if you want to know ",a.createElement("em",null,"why")," that conversion works, let's do some maths!"),a.createElement("div",{className:"note"},a.createElement("h2",{id:"deriving-the-conversion-formulae"},"Deriving the conversion formulae"),a.createElement("p",null,"In order to convert between Catmull-Rom curves and B\xE9zier curves, we need to know two things. Firstly, how to express the Catmull-Rom curve using a \"set of four coordinates\", rather than a mix of coordinates and tangents, and secondly, how to convert those Catmull-Rom coordinates to and from B\xE9zier form."),a.createElement("p",null,"So, let's start with the first, where we want to satisfy the following equality:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5a61445ae5395b5949e2cd5844aa0f89dc7aad47.svg",width:"196",height:"86.8"}),a.createElement("p",null,"This mapping says that in order to map a Catmull-Rom \"point + tangent\" vector to something based on an \"all coordinates\" vector, we need to determine the mapping matrix such that applying ",a.createElement("em",null,"T")," yields P2 as start point, P3 as end point, and two tangents based on the lines between P1 and P3, and P2 nd P4, respectively."),a.createElement("p",null,"Computing ",a.createElement("em",null,"T")," is really more \"arranging the numbers\":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2fd035ec60c3a841756808e5cf3f0dee53f7624a.svg",width:"620.1999999999999",height:"86.8"}),a.createElement("p",null,"Thus:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/7b8a0f667d2c6f007bb156fc242614ad8dbc901a.svg",width:"149.79999999999998",height:"85.39999999999999"}),a.createElement("p",null,"However, we're not ",a.createElement("em",null,"quite")," done, because Catmull-Rom curves have a parameter called \"tension\", written as \u03C4 (\"tau\"), which is a scaling factor for the tangent vectors: the bigger the tension, the smaller the tangents, and the smaller the tension, the bigger the tangents. As such, the tension factor goes in the denominator for the tangents, and before we continue, let's add that tension factor into both our coordinate vector representation, and mapping matrix ",a.createElement("em",null,"T"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5ac13a052456cb20ac2cbe2a1a3691b949d8e1b5.svg",width:"299.59999999999997",height:"88.19999999999999"}),a.createElement("p",null,"With the mapping matrix properly done, let's rewrite the \"point + tangent\" Catmull-Rom matrix form to a matrix form in terms of four coordinates, and see what we end up with:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f7ca80d722bc33c5f63d0a74811e5dba6268c2f8.svg",width:"429.79999999999995",height:"78.39999999999999"}),a.createElement("p",null,"Replace point/tangent vector with the expression for all-coordinates:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b2fef1714537dce7572d220ca8e58711dc5064d0.svg",width:"576.8",height:"85.39999999999999"}),a.createElement("p",null,"and merge the matrices:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2ee74d984303a352038c8c9a2299a11b0b74f480.svg",width:"477.4",height:"88.19999999999999"}),a.createElement("p",null,"This looks a lot like the B\xE9zier matrix form, which as we saw in the chapter on B\xE9zier curves, should look like this:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/fa5444bb0c097ce9f3ba531953162e61c382755a.svg",width:"371",height:"77"}),a.createElement("p",null,"So, if we want to express a Catmull-Rom curve using a B\xE9zier curve, we'll need to turn this Catmull-Rom bit:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5ba765e29b786f9a838291b17e82b773a5f3877c.svg",width:"237.99999999999997",height:"88.19999999999999"}),a.createElement("p",null,"Into something that looks like this:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/da1cb21bae7f45be5fd2adf910372f6642e8228c.svg",width:"175",height:"77"}),a.createElement("p",null,"And the way we do that is with a fairly straight forward bit of matrix rewriting. We start with the equality we need to ensure:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/93d9fe77ab96845b0029662e766c8249d55d51ba.svg",width:"461.99999999999994",height:"88.19999999999999"}),a.createElement("p",null,"Then we remove the coordinate vector from both sides without affecting the equality:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b0d52c1f7414d26f8cf2aa8657479e2a0ae5c373.svg",width:"371",height:"88.19999999999999"}),a.createElement("p",null,"Then we can \"get rid of\" the B\xE9zier matrix on the right by left-multiply both with the inverse of the B\xE9zier matrix:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/353ca3c64d13b6d1f8138d59f059a33bd256a0fb.svg",width:"690.1999999999999",height:"92.39999999999999"}),a.createElement("p",null,"A matrix times its inverse is the matrix equivalent of 1, and because \"something times 1\" is the same as \"something\", so we can just outright remove any matrix/inverse pair:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/01514ce85f8c4820eced8617140758104183166f.svg",width:"387.79999999999995",height:"92.39999999999999"}),a.createElement("p",null,"And now we're ",a.createElement("em",null,"basically")," done. We just multiply those two matrices and we know what ",a.createElement("em",null,"V")," is:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/fb0018e21685384c5a39e16738e3dc324b5ca863.svg",width:"169.39999999999998",height:"81.19999999999999"}),a.createElement("p",null,"We now have the final piece of our function puzzle. Let's run through each step."),a.createElement("ol",null,a.createElement("li",null,"Start with the Catmull-Rom function:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f7ca80d722bc33c5f63d0a74811e5dba6268c2f8.svg",width:"429.79999999999995",height:"78.39999999999999"}),a.createElement("ol",{start:"2"},a.createElement("li",null,"rewrite to pure coordinate form:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/921d4e7e4d7f835372650365f5a6351e065482c6.svg",width:"340.2",height:"88.19999999999999"}),a.createElement("ol",{start:"3"},a.createElement("li",null,"rewrite for \"normal\" coordinate vector:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/8129cdce2d9f80d8fd665524329fb7ab6501d9d6.svg",width:"463.4",height:"85.39999999999999"}),a.createElement("ol",{start:"4"},a.createElement("li",null,"merge the inner matrices:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/e8aa6936c758a88b9ea90ae0b553cfb729d02acc.svg",width:"365.4",height:"88.19999999999999"}),a.createElement("ol",{start:"5"},a.createElement("li",null,"rewrite for B\xE9zier matrix form:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/8961f5322e4e0cd09791647d8d4d3120c567ba21.svg",width:"452.2",height:"81.19999999999999"}),a.createElement("ol",{start:"6"},a.createElement("li",null,"and transform the coordinates so we have a \"pure\" B\xE9zier expression:")),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/9e68f80b270d3445d9f9cb28ff2c5aed219aa9d2.svg",width:"365.4",height:"85.39999999999999"}),a.createElement("p",null,"And we're done: we finally know how to convert these two curves!")),a.createElement("p",null,"If we have a Catmull-Rom curve defined by four coordinates P",a.createElement("sub",null,"1")," through P",a.createElement("sub",null,"4"),", then we can draw that curve using a B\xE9zier curve that has the vector:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/92a34d777899da97f1907e6b093db28872f02c3a.svg",width:"261.8",height:"89.6"}),a.createElement("p",null,"Similarly, if we have a B\xE9zier curve defined by four coordinates P",a.createElement("sub",null,"1")," through P",a.createElement("sub",null,"4"),", we can draw that using a standard tension Catmull-Rom curve with the following coordinate values:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/0717f4e47237b8f84b226b28626ccc500308b896.svg",width:"298.2",height:"81.19999999999999"}),a.createElement("p",null,"or, if your API requires specifying Catmull-Rom curves using \"point + tangent\" form:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/56546179da07b8e92a22210a8dac3f4b3dbc4e58.svg",width:"298.2",height:"81.19999999999999"}))}},catmullmoulding:{locale:"en-GB",title:"Creating a Catmull-Rom curve from three points",getContent:function(e){return a.createElement("section",{className:"catmullmoulding"},a.createElement(r,{name:"catmullmoulding",title:"Creating a Catmull-Rom curve from three points",number:"35"}),a.createElement("p",null,"Now, we saw how to fit a B\xE9zier curve to three points, but if Catmull-Rom curves go through points, why can't we just use those to do curve fitting, instead?"),a.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."),a.createElement("p",null,"Using Catmull-Rom curves, we need virtually no computation, but even though we end up with one Catmull-Rom curve of ",a.createElement("i",null,"n")," points, in order to draw the equivalent curve using cubic B\xE9zier curves we need a massive ",a.createElement("i",null,"3n-2")," points (and that's without double-counting points that are shared by consecutive cubic curves)."),a.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:"),a.createElement(i,{handler:e.props.handler,section:"catmullmoulding",title:"Catmull-Rom curve fitting",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}),a.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\xE9zier form we're going to end up with a lot of separate (but visually joined) B\xE9zier 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."))}},polybezier:{locale:"en-GB",title:"Forming poly-B\xE9zier curves",getContent:function(e){return a.createElement("section",{className:"polybezier"},a.createElement(r,{name:"polybezier",title:"Forming poly-B\xE9zier curves",number:"36"}),a.createElement("p",null,"Much like lines can be chained together to form polygons, B\xE9zier curves can be chained together to form poly-B\xE9ziers, and the only trick required is to make sure that:"),a.createElement("ol",null,a.createElement("li",null,"the end point of each section is the starting point of the following section, and"),a.createElement("li",null,"the derivatives across that dual point line up.")),a.createElement("p",null,"Unless you want sharp corners, of course. Then you don't even need 2."),a.createElement("p",null,"We'll cover three forms of poly-B\xE9zier 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\xE9ziers that are pretty hard to work with, but they're the easiest to implement:"),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Unlinked quadratic poly-B\xE9zier",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw"}),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Unlinked cubic poly-B\xE9zier",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw"}),a.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:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/37740bb1a0b7b1ff48bf3454e52295fc717cacbb.svg",width:"130.2",height:"18.2"}),a.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:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ce6e3939608c4ed0598107b06543c2301b91bb7f.svg",width:"319.2",height:"42"}),a.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\xE9zier curve again, but this time moving the control points around moves others, too. However, you might see something unexpected going on for quadratic curves..."),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Connected quadratic poly-B\xE9zier",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onMouseMove:e.linkDerivatives}),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Connected cubic poly-B\xE9zier",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onMouseMove:e.linkDerivatives}),a.createElement("p",null,"As you can see, quadratic curves are particularly ill-suited for poly-B\xE9zier 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\xE9ziers 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."),a.createElement("p",null,"So: let's relax the requirement a little."),a.createElement("p",null,"We can change the constraint so that we still preserve the ",a.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 ",a.createElement("em",null,"vector length"),". Doing so will give us a much more useful kind of poly-B\xE9zier curve:"),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Angularly connected quadratic poly-B\xE9zier",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onMouseMove:e.linkDirection}),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Angularly connected cubic poly-B\xE9zier",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onMouseMove:e.linkDirection}),a.createElement("p",null,"Cubic curves are now better behaved when it comes to dragging control points around, but the quadratic poly-B\xE9zier 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..."),a.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."),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Standard connected quadratic poly-B\xE9zier",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onMouseDown:e.bufferPoints,onMouseMove:e.modelCurve}),a.createElement(i,{handler:e.props.handler,section:"polybezier",title:"Standard connected cubic poly-B\xE9zier",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onMouseDown:e.bufferPoints,onMouseMove:e.modelCurve}),a.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..."),a.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 exercise for the reader."))}},shapes:{locale:"en-GB",title:"Boolean shape operations",getContent:function(e){return a.createElement("section",{className:"shapes"},a.createElement(r,{name:"shapes",title:"Boolean shape operations",number:"37"}),a.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\xE9zier curves. For simplicity (well... sort of, more homogeneity), we'll be looking at poly-B\xE9zier shapes only, but a shape that consists of a mix of lines and B\xE9zier 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\xE9zier curves. Since poly-B\xE9zier curves are a superset, we'll be using those in the following examples.)"),a.createElement("p",null,"The procedure for performing boolean operations consists, broadly, of four steps:"),a.createElement("ol",null,a.createElement("li",null,"Find the intersection points between both shapes,"),a.createElement("li",null,"cut up the shapes into multiple sections between these intersections,"),a.createElement("li",null,"discard any section that isn't part of the desired operation's resultant shape, and"),a.createElement("li",null,"link up the remaining sections to form the new shape.")),a.createElement("p",null,"Finding all intersections between two poly-B\xE9zier 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\xE9zier curve, we check whether its bounding box overlaps with any of the segment bounding boxes in the other poly-B\xE9zier curve. If so, we run normal intersection detection."),a.createElement("p",null,"After finding all intersection points, we split up our poly-B\xE9zier curves, and make sure to record which of the newly formed poly-B\xE9zier curves might potentially link up at the points we split the originals up at. This will let us quickly glue poly-B\xE9zier curves back together after the next step."),a.createElement("p",null,"Once we have all the new poly-B\xE9zier curves, we run the first step of the desired boolean operation."),a.createElement("ul",null,a.createElement("li",null,"Union: discard all poly-B\xE9zier 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."),a.createElement("li",null,"Intersection: discard all poly-B\xE9zier 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."),a.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.")),a.createElement("table",{className:"sketch"},a.createElement("tbody",null,a.createElement("tr",null,a.createElement("td",{className:"labeled-image"},a.createElement("img",{src:"images/op_base.gif",height:"169"}),"Two overlapping shapes."),a.createElement("td",{className:"labeled-image"},a.createElement("img",{src:"images/op_union.gif",height:"169"}),"The unified region."),a.createElement("td",{className:"labeled-image"},a.createElement("img",{src:"images/op_intersection.gif",height:"169"}),"Their intersection."),a.createElement("td",{className:"labeled-image"},a.createElement("img",{src:"images/op_exclusion.gif",height:"169"}),"Their exclusion regions.")))),a.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 ",a.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)."),a.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 ",a.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."),a.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."),a.createElement(i,{handler:e.props.handler,section:"shapes",title:"Boolean shape operations with Paper.js",paperjs:!0,setup:e.setup,sname:"setup",draw:e.draw,dname:"draw",onMouseMove:e.onMouseMove},a.createElement("br",null),e.modes.map(function(t){var n=e.state.mode===t?"selected":null;return a.createElement("button",{className:n,key:t,onClick:function(){return e.setMode(t)}},t)})))}},projections:{locale:"en-GB",title:"Projecting a point onto a B\xE9zier curve",getContent:function(e){return a.createElement("section",{className:"projections"},a.createElement(r,{name:"projections",title:"Projecting a point onto a B\xE9zier curve",number:"38"}),a.createElement("p",null,"Say we have a B\xE9zier curve and some point, not on the curve, of which we want to know which ",a.createElement("code",null,"t")," value on the curve gives us an on-curve point closest to our off-curve point. Or: say we want to find the projection of a random point onto a curve. How do we do that?"),a.createElement("p",null,"If the B\xE9zier curve is of low enough order, we might be able to ",a.createElement("a",{href:"https://web.archive.org/web/20140713004709/http://jazzros.blogspot.com/2011/03/projecting-point-on-bezier-curve.html"},"work out the maths for how to do this"),", and get a perfect ",a.createElement("code",null,"t")," value back, but in general this is an incredibly hard problem and the easiest solution is, really, a numerical approach again. We'll be finding our ideal ",a.createElement("code",null,"t")," value using a ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Binary_search_algorithm"},"binary search"),". First, we do a coarse distance-check based on ",a.createElement("code",null,"t")," values associated with the curve's \"to draw\" coordinates (using a lookup table, or LUT). This is pretty fast. Then we run this algorithm:"),a.createElement("ol",null,a.createElement("li",null,"with the ",a.createElement("code",null,"t")," value we found, start with some small interval around ",a.createElement("code",null,"t")," (1/length_of_LUT on either side is a reasonable start),"),a.createElement("li",null,"if the distance to ",a.createElement("code",null,"t \xB1 interval/2")," is larger than the distance to ",a.createElement("code",null,"t"),", try again with the interval reduced to half its original length."),a.createElement("li",null,"if the distance to ",a.createElement("code",null,"t \xB1 interval/2")," is smaller than the distance to ",a.createElement("code",null,"t"),", replace ",a.createElement("code",null,"t")," with the smaller-distance value."),a.createElement("li",null,"after reducing the interval, or changing ",a.createElement("code",null,"t"),", go back to step 1.")),a.createElement("p",null,"We keep repeating this process until the interval is small enough to claim the difference in precision found is irrelevant for the purpose we're trying to find ",a.createElement("code",null,"t")," for. In this case, I'm arbitrarily fixing it at 0.0001."),a.createElement("p",null,"The following graphic demonstrates the result of this procedure. Simply move the cursor around, and if it does not lie on top of the curve, you will see a line that projects the cursor onto the curve based on an iteratively found \"ideal\" ",a.createElement("code",null,"t")," value."),a.createElement(i,{handler:e.props.handler,section:"projections",title:"Projecting a point onto a B\xE9zier curve",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw",onMouseMove:e.onMouseMove}))}},offsetting:{locale:"en-GB",title:"Curve offsetting",getContent:function(e){return a.createElement("section",{className:"offsetting"},a.createElement(r,{name:"offsetting",title:"Curve offsetting",number:"39"}),a.createElement("p",null,"Perhaps you're like me, and you've been writing various small programs that use B\xE9zier curves in some way or another, and at some point you make the step to implementing path extrusion. But you don't want to do it pixel based; you want to stay in the vector world. You find that extruding lines is relatively easy, and tracing outlines is coming along nicely (although junction caps and fillets are a bit of a hassle), and then you decide to do things properly and add B\xE9zier curves to the mix. Now you have a problem."),a.createElement("p",null,"Unlike lines, you can't simply extrude a B\xE9zier curve by taking a copy and moving it around, because of the curvatures; rather than a uniform thickness, you get an extrusion that looks too thin in places, if you're lucky, but more likely will self-intersect. The trick, then, is to scale the curve, rather than simply copying it. But how do you scale a B\xE9zier curve?"),a.createElement("p",null,"Bottom line: ",a.createElement("strong",null,"you can't"),". So you cheat. We're not going to do true curve scaling, or rather curve offsetting, because that's impossible. Instead we're going to try to generate 'looks good enough' offset curves."),a.createElement("div",{className:"note"},a.createElement("h3",{id:"what-do-you-mean-you-can-t-prove-it-"},"\"What do you mean, 'you can't'? Prove it.\""),a.createElement("p",null,"First off, when I say \"you can't,\" what I really mean is \"you can't offset a B\xE9zier curve with another B\xE9zier curve\", not even by using a really high order curve. You can find the function that describes the offset curve, but it won't be a polynomial, and as such it cannot be represented as a B\xE9zier curve, which ",a.createElement("strong",null,"has")," to be a polynomial. Let's look at why this is:"),a.createElement("p",null,"From a mathematical point of view, an offset curve ",a.createElement("code",null,"O(t)")," is a curve such that, given our original curve ",a.createElement("code",null,"B(t)"),", any point on ",a.createElement("code",null,"O(t)")," is a fixed distance ",a.createElement("code",null,"d")," away from coordinate ",a.createElement("code",null,"B(t)"),". So let's math that:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/3aff5cef0028337bbb48ae64ad30000c4d5e238f.svg",width:"113.39999999999999",height:"16.799999999999997"}),a.createElement("p",null,"However, we're working in 2D, and ",a.createElement("code",null,"d")," is a single value, so we want to turn it into a vector. If we want a point distance ",a.createElement("code",null,"d")," \"away\" from the curve ",a.createElement("code",null,"B(t)")," then what we really mean is that we want a point at ",a.createElement("code",null,"d")," times the \"normal vector\" from point ",a.createElement("code",null,"B(t)"),", where the \"normal\" is a vector that runs perpendicular (\"at a right angle\") to the tangent at ",a.createElement("code",null,"B(t)"),". Easy enough:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/2cf48e2f8525258a3fa0fe4f10ec2acef67104b3.svg",width:"158.2",height:"16.799999999999997"}),a.createElement("p",null,"Now this still isn't very useful unless we know what the formula for ",a.createElement("code",null,"N(t)")," is, so let's find out. ",a.createElement("code",null,"N(t)")," runs perpendicular to the original curve tangent, and we know that the tangent is simply ",a.createElement("code",null,"B'(t)"),", so we could just rotate that 90 degrees and be done with it. However, we need to ensure that ",a.createElement("code",null,"N(t)")," has the same magnitude for every ",a.createElement("code",null,"t"),", or the offset curve won't be at a uniform distance, thus not being an offset curve at all. The easiest way to guarantee this is to make sure ",a.createElement("code",null,"N(t)")," always has length 1, which we can achieve by dividing ",a.createElement("code",null,"B'(t)")," by its magnitude:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/4941ecbff4c50732ba66fec53307456fc605f032.svg",width:"125.99999999999999",height:"42"}),a.createElement("p",null,"Determining the length requires computing an arc length, and this is where things get Tricky with a capital T. First off, to compute arc length from some start ",a.createElement("code",null,"a")," to end ",a.createElement("code",null,"b"),", we must use the formula we saw earlier. Noting that \"length\" is usually denoted with double vertical bars:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/f6d8c2965b02363e092acb00bbc1398cfbb170a4.svg",width:"177.79999999999998",height:"37.8"}),a.createElement("p",null,"So if we want the length of the tangent, we plug in ",a.createElement("code",null,"B'(t)"),", with ",a.createElement("code",null,"t = 0")," as start and",a.createElement("code",null,"t = 1")," as end:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/1f024282044316a9e4b3de2c855d2ceb96aff056.svg",width:"219.79999999999998",height:"37.8"}),a.createElement("p",null,"And that's where things go wrong. It doesn't even really matter what the second derivative for ",a.createElement("code",null,"B(t)")," is, that square root is screwing everything up, because it turns our nice polynomials into things that are no longer polynomials."),a.createElement("p",null,"There is a small class of polynomials where the square root is also a polynomial, but they're utterly useless to us: any polynomial with unweighted binomial coefficients has a square root that is also a polynomial. Now, you might think that B\xE9zier curves are just fine because they do, but they don't; remember that only the ",a.createElement("strong",null,"base")," function has binomial coefficients. That's before we factor in our coordinates, which turn it into a non-binomial polygon. The only way to make sure the functions stay binomial is to make all our coordinates have the same value. And that's not a curve, that's a point. We can already create offset curves for points, we call them circles, and they have much simpler functions than B\xE9zier curves."),a.createElement("p",null,"So, since the tangent length isn't a polynomial, the normalised tangent won't be a polynomial either, which means ",a.createElement("code",null,"N(t)")," won't be a polynomial, which means that ",a.createElement("code",null,"d")," times ",a.createElement("code",null,"N(t)")," won't be a polynomial, which means that, ultimately, ",a.createElement("code",null,"O(t)")," won't be a polynomial, which means that even if we can determine the function for ",a.createElement("code",null,"O(t)")," just fine (and that's far from trivial!), it simply cannot be represented as a B\xE9zier curve."),a.createElement("p",null,"And that's one reason why B\xE9zier curves are tricky: there are actually a ",a.createElement("em",null,"lot")," of curves that cannot be represented as a B\xE9zier curve at all. They can't even model their own offset curves. They're weird that way. So how do all those other programs do it? Well, much like we're about to do, they cheat. We're going to approximate an offset curve in a way that will look relatively close to what the real offset curve would look like, if we could compute it.")),a.createElement("p",null,"So, you cannot offset a B\xE9zier curve perfectly with another B\xE9zier curve, no matter how high-order you make that other B\xE9zier curve. However, we can chop up a curve into \"safe\" sub-curves (where \"safe\" means that all the control points are always on a single side of the baseline, and the midpoint of the curve at ",a.createElement("code",null,"t=0.5")," is roughly in the center of the polygon defined by the curve coordinates) and then point-scale each sub-curve with respect to its scaling origin (which is the intersection of the point normals at the start and end points)."),a.createElement("p",null,"A good way to do this reduction is to first find the curve's extreme points, as explained in the earlier section on curve extremities, and use these as initial splitting points. After this initial split, we can check each individual segment to see if it's \"safe enough\" based on where the center of the curve is. If the on-curve point for ",a.createElement("code",null,"t=0.5")," is too far off from the center, we simply split the segment down the middle. Generally this is more than enough to end up with safe segments."),a.createElement("p",null,"The following graphics show off curve offsetting, and you can use your up and down arrow keys to control the distance at which the curve gets offset. The curve first gets reduced to safe segments, each of which is then offset at the desired distance. Especially for simple curves, particularly easily set up for quadratic curves, no reduction is necessary, but the more twisty the curve gets, the more the curve needs to be reduced in order to get segments that can safely be scaled."),a.createElement(i,{handler:e.props.handler,section:"offsetting",title:"Offsetting a quadratic B\xE9zier curve",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}),a.createElement(i,{handler:e.props.handler,section:"offsetting",title:"Offsetting a cubic B\xE9zier curve",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}),a.createElement("p",null,"You may notice that this may still lead to small 'jumps' in the sub-curves when moving the curve around. This is caused by the fact that we're still performing a naive form of offsetting, moving the control points the same distance as the start and end points. If the curve is large enough, this may still lead to incorrect offsets."))}},graduatedoffset:{locale:"en-GB",title:"Graduated curve offsetting",getContent:function(e){return a.createElement("section",{className:"graduatedoffset"},a.createElement(r,{name:"graduatedoffset",title:"Graduated curve offsetting",number:"40"}),a.createElement("p",null,"What if we want to do graduated offsetting, starting at some distance ",a.createElement("code",null,"s")," but ending at some other distance ",a.createElement("code",null,"e"),"? Well, if we can compute the length of a curve (which we can if we use the Legendre-Gauss quadrature approach) then we can also determine how far \"along the line\" any point on the curve is. With that knowledge, we can offset a curve so that its offset curve is not uniformly wide, but graduated between with two different offset widths at the start and end."),a.createElement("p",null,"Like normal offsetting we cut up our curve in sub-curves, and then check at which distance along the original curve each sub-curve starts and ends, as well as to which point on the curve each of the control points map. This gives us the distance-along-the-curve for each interesting point in the sub-curve. If we call the total length of all sub-curves seen prior to seeing \"the current\" sub-curve ",a.createElement("code",null,"S")," (and if the current sub-curve is the first one, ",a.createElement("code",null,"S")," is zero), and we call the full length of our original curve ",a.createElement("code",null,"L"),", then we get the following graduation values:"),a.createElement("ul",null,a.createElement("li",null,"start: map ",a.createElement("code",null,"S")," from interval (",a.createElement("code",null,"0,L"),") to interval ",a.createElement("code",null,"(s,e)")),a.createElement("li",null,"c1: ",a.createElement("code",null,"map(S+d1, 0,L, s,e)"),", d1 = distance along curve to projection of c1"),a.createElement("li",null,"c2: ",a.createElement("code",null,"map(S+d2, 0,L, s,e)"),", d2 = distance along curve to projection of c2"),a.createElement("li",null,"..."),a.createElement("li",null,"end: ",a.createElement("code",null,"map(S+length(subcurve), 0,L, s,e)"))),a.createElement("p",null,"At each of the relevant points (start, end, and the projections of the control points onto the curve) we know the curve's normal, so offsetting is simply a matter of taking our original point, and moving it along the normal vector by the offset distance for each point. Doing so will give us the following result (these have with a starting width of 0, and an end width of 40 pixels, but can be controlled with your up and down arrow keys):"),a.createElement(i,{handler:e.props.handler,section:"graduatedoffset",title:"Offsetting a quadratic B\xE9zier curve",setup:e.setupQuadratic,sname:"setupQuadratic",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}),a.createElement(i,{handler:e.props.handler,section:"graduatedoffset",title:"Offsetting a cubic B\xE9zier curve",setup:e.setupCubic,sname:"setupCubic",draw:e.draw,dname:"draw",onKeyDown:e.props.onKeyDown}))}},circles:{locale:"en-GB",title:"Circles and quadratic B\xE9zier curves",getContent:function(e){return a.createElement("section",{className:"circles"},a.createElement(r,{name:"circles",title:"Circles and quadratic B\xE9zier curves",number:"41"}),a.createElement("p",null,"Circles and B\xE9zier curves are very different beasts, and circles are infinitely easier to work with than B\xE9zier curves. Their formula is much simpler, and they can be drawn more efficiently. But, sometimes you don't have the luxury of using circles, or ellipses, or arcs. Sometimes, all you have are B\xE9zier curves. For instance, if you're doing font design, fonts have no concept of geometric shapes, they only know straight lines, and B\xE9zier curves. OpenType fonts with TrueType outlines only know quadratic B\xE9zier curves, and OpenType fonts with Type 2 outlines only know cubic B\xE9zier curves. So how do you draw a circle, or an ellipse, or an arc?"),a.createElement("p",null,"You approximate."),a.createElement("p",null,"We already know that B\xE9zier curves cannot model all curves that we can think of, and this includes perfect circles, as well as ellipses, and their arc counterparts. However, we can certainly approximate them to a degree that is visually acceptable. Quadratic and cubic curves offer us different curvature control, so in order to approximate a circle we will first need to figure out what the error is if we try to approximate arcs of increasing degree with quadratic and cubic curves, and where the coordinates even lie."),a.createElement("p",null,"Since arcs are mid-point-symmetrical, we need the control points to set up a symmetrical curve. For quadratic curves this means that the control point will be somewhere on a line that intersects the baseline at a right angle. And we don't get any choice on where that will be, since the derivatives at the start and end point have to line up, so our control point will lie at the intersection of the tangents at the start and end point."),a.createElement("p",null,"First, let's try to fit the quadratic curve onto a circular arc. In the following sketch you can move the mouse around over a unit circle, to see how well, or poorly, a quadratic curve can approximate the arc from (1,0) to where your mouse cursor is:"),a.createElement(i,{handler:e.props.handler,section:"circles",title:"Quadratic B\xE9zier arc approximation",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw",onMouseMove:e.onMouseMove}),a.createElement("p",null,"As you can see, things go horribly wrong quite quickly; even trying to approximate a quarter circle using a quadratic curve is a bad idea. An eighth of a turns might look okay, but how okay is okay? Let's apply some maths and find out. What we're interested in is how far off our on-curve coordinates are with respect to a circular arc, given a specific start and end angle. We'll be looking at how much space there is between the circular arc, and the quadratic curve's midpoint."),a.createElement("p",null,"We start out with our start and end point, and for convenience we will place them on a unit circle (a circle around 0,0 with radius 1), at some angle ",a.createElement("em",null,"\u03C6"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ef34ab8f466ed3294895135a346b55ada05d779d.svg",width:"183.39999999999998",height:"42"}),a.createElement("p",null,"What we want to find is the intersection of the tangents, so we want a point C such that:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/5660e8512b07dbac7fcf04633de8002fa25aa962.svg",width:"298.2",height:"42"}),a.createElement("p",null,"i.e. we want a point that lies on the vertical line through S (at some distance ",a.createElement("em",null,"a")," from S) and also lies on the tangent line through E (at some distance ",a.createElement("em",null,"b")," from E). Solving this gives us:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/d16e7a1c1e9686e1afb82f4ffcec07078d264565.svg",width:"229.6",height:"42"}),a.createElement("p",null,"First we solve for ",a.createElement("em",null,"b"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/3128b31a874166ebe4479d3002d70f280de375a1.svg",width:"588",height:"18.2"}),a.createElement("p",null,"which yields:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/02b158f9ef2191b970dc2fe69c0903eba2b1f8b5.svg",width:"106.39999999999999",height:"40.599999999999994"}),a.createElement("p",null,"which we can then substitute in the expression for ",a.createElement("em",null,"a"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/3bd9c2d6740ff530aabcbe60252742032af816e9.svg",width:"242.2",height:"204.39999999999998"}),a.createElement("p",null,"A quick check shows that plugging these values for ",a.createElement("em",null,"a")," and ",a.createElement("em",null,"b")," into the expressions for C",a.createElement("sub",null,"x")," and C",a.createElement("sub",null,"y")," give the same x/y coordinates for both \"",a.createElement("em",null,"a")," away from A\" and \"",a.createElement("em",null,"b")," away from B\", so let's continue: now that we know the coordinate values for C, we know where our on-curve point T for ",a.createElement("em",null,"t=0.5")," (or angle \u03C6/2) is, because we can just evaluate the B\xE9zier polynomial, and we know where the circle arc's actual point P is for angle \u03C6/2:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/0b80423188012451e0400f473c19729eb2bad654.svg",width:"197.39999999999998",height:"33.599999999999994"}),a.createElement("p",null,"We compute T, observing that if ",a.createElement("em",null,"t=0.5"),", the polynomial values (1-t)\xB2, 2(1-t)t, and t\xB2 are 0.25, 0.5, and 0.25 respectively:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/bc50559ff8bd9062694a449aae5f6f85f91de909.svg",width:"264.59999999999997",height:"36.4"}),a.createElement("p",null,"Which, worked out for the x and y components, gives:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c7fca7664a3acb855eeaaf412aa2331202f41097.svg",width:"428.4",height:"81.19999999999999"}),a.createElement("p",null,"And the distance between these two is the standard Euclidean distance:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/8eb14f8c2bbee9d6cdb0ecb995f45e58f9a9a0a5.svg",width:"418.59999999999997",height:"161"}),a.createElement("p",null,"So, what does this distance function look like when we plot it for a number of ranges for the angle \u03C6, such as a half circle, quarter circle and eighth circle?"),a.createElement("table",null,a.createElement("tbody",null,a.createElement("tr",null,a.createElement("td",null,a.createElement("img",{src:"images/arc-q-pi.gif",height:"190"}),"plotted for 0 \u2264 \u03C6 \u2264 \u03C0:"),a.createElement("td",null,a.createElement("img",{src:"images/arc-q-pi2.gif",height:"187"}),"plotted for 0 \u2264 \u03C6 \u2264 \xBD\u03C0:"),a.createElement("td",null,e.props.showhref?"http://www.wolframalpha.com/input/?i=plot+sqrt%28%281%2F4+*+%28sin%28x%29+%2B+2tan%28x%2F2%29%29+-+sin%28x%2F2%29%29%5E2+%2B+%282sin%5E4%28x%2F4%29%29%5E2%29+for+0+%3C%3D+x+%3C%3D+pi%2F4":null,a.createElement("img",{src:"images/arc-q-pi4.gif",height:"174"}),"plotted for 0 \u2264 \u03C6 \u2264 \xBC\u03C0:")))),a.createElement("p",null,"We now see why the eighth circle arc looks decent, but the quarter circle arc doesn't: an error of roughly 0.06 at ",a.createElement("em",null,"t=0.5")," means we're 6% off the mark... we will already be off by one pixel on a circle with pixel radius 17. Any decent sized quarter circle arc, say with radius 100px, will be way off if approximated by a quadratic curve! For the eighth circle arc, however, the error is only roughly 0.003, or 0.3%, which explains why it looks so close to the actual eighth circle arc. In fact, if we want a truly tiny error, like 0.001, we'll have to contend with an angle of (rounded) 0.593667, which equates to roughly 34 degrees. We'd need 11 quadratic curves to form a full circle with that precision! (technically, 10 and ten seventeenth, but we can't do partial curves, so we have to round up). That's a whole lot of curves just to get a shape that can be drawn using a simple function!"),a.createElement("p",null,"In fact, let's flip the function around, so that if we plug in the precision error, labelled \u03B5, we get back the maximum angle for that precision:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/61a938fa10b77e8c41c3c064ed39bd1145d6bbcc.svg",width:"259",height:"56"}),a.createElement("p",null,"And frankly, things are starting to look a bit ridiculous at this point, we're doing way more maths than we've ever done, but thankfully this is as far as we need the maths to take us: If we plug in the precisions 0.1, 0.01, 0.001 and 0.0001 we get the radians values 1.748, 1.038, 0.594 and 0.3356; in degrees, that means we can cover roughly 100 degrees (requiring four curves), 59.5 degrees (requiring six curves), 34 degrees (requiring 11 curves), and 19.2 degrees (requiring a whopping nineteen curves)."),a.createElement("p",null,"The bottom line? ",a.createElement("strong",null,"Quadratic curves are kind of lousy")," if you want circular (or elliptical, which are circles that have been squashed in one dimension) curves. We can do better, even if it's just by raising the order of our curve once. So let's try the same thing for cubic curves."))}},circles_cubic:{locale:"en-GB",title:"Circles and cubic B\xE9zier curves",getContent:function(e){return a.createElement("section",{className:"circles_cubic"},a.createElement(r,{name:"circles_cubic",title:"Circles and cubic B\xE9zier curves",number:"42"}),a.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?"),a.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."),a.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."),a.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:"),a.createElement(i,{handler:e.props.handler,section:"circles_cubic",title:"Cubic B\xE9zier arc approximation",setup:e.setup,sname:"setup",draw:e.draw,dname:"draw",onMouseMove:e.onMouseMove}),a.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."),a.createElement("p",null,"We can already see that cubic curves are a lot better than quadratic curves, and don't look all that wrong until we go well past a quarter circle; \u215Cth 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!"),a.createElement("p",null,"So, maths time again: how okay is \"okay\"? Let's apply some more maths to find out."),a.createElement("p",null,"Unlike for the quadratic curve, we can't use ",a.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 ",a.createElement("i",null,"t")," value. If we run some analysis on the curve we find that the actual ",a.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."),a.createElement("p",null,"So instead of walking you through the derivation for that value, let's simply take that ",a.createElement("i",null,"t")," value and see what the error is for circular arcs with an angle ranging from 0 to 2\u03C0:"),a.createElement("table",null,a.createElement("tbody",null,a.createElement("tr",null,a.createElement("td",null,a.createElement("img",{src:"images/arc-c-2pi.gif",height:"187"}),"plotted for 0 \u2264 \u03C6 \u2264 2\u03C0:"),a.createElement("td",null,a.createElement("img",{src:"images/arc-c-pi.gif",height:"187"}),"plotted for 0 \u2264 \u03C6 \u2264 \u03C0:"),a.createElement("td",null,a.createElement("img",{src:"images/arc-c-pi2.gif",height:"187"}),"plotted for 0 \u2264 \u03C6 \u2264 \xBD\u03C0:")))),a.createElement("p",null,"We see that cubic B\xE9zier 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!"),a.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\xE9zier 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."),a.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:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ef34ab8f466ed3294895135a346b55ada05d779d.svg",width:"183.39999999999998",height:"42"}),a.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:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/4df65dae78bc5a0e6c5f23a2faae9a9d7a8b39b3.svg",width:"118.99999999999999",height:"42"}),a.createElement("p",null,"where \"a\" is some scaling factor, and:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/cb32f8f9c3ae2b264a48003c237a798d02dc8935.svg",width:"170.79999999999998",height:"42"}),a.createElement("p",null,"where \"b\" is also some scaling factor."),a.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 trigonometric identities, so if you just want to see the final result just skip past the next section!"),a.createElement("div",{className:"note"},a.createElement("h2",{id:"let-s-do-this-thing-"},"Let's do this thing."),a.createElement("p",null,"Unlike for the quadratic case, we need some more information in order to compute ",a.createElement("i",null,"a")," and ",a.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",a.createElement("sub",null,"1")," will apply to C",a.createElement("sub",null,"2")," as well (rotated along its tangent), so we'll focus on finding the location of C",a.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."),a.createElement("p",null,"If we look at the triangle that is formed between our starting point, or initial guess C",a.createElement("sub",null,"1")," and our real C",a.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 hypotenuse, then the angle for the corner hypotenuse/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 ",a.createElement("i",null,"t=0.5")," value."),a.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 ",a.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",a.createElement("sub",null,"1")," = ","{","A,B","}"," + d",a.createElement("sub",null,"2")," = ","{","B,C","}",":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/b15a274c1e0a6aeeaf517b5d2c8ee0a7997dd617.svg",width:"417.2",height:"42"}),a.createElement("p",null,"So that just leaves us to find the distance from ",a.createElement("i",null,"t=0.5")," to the baseline for an arbitrary angle \u03C6, which is the distance from the centre of the circle to our ",a.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:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/0b80423188012451e0400f473c19729eb2bad654.svg",width:"197.39999999999998",height:"33.599999999999994"}),a.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:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/9be55fb38d5d30bbc6c7140afb1c7bc097bc044e.svg",width:"274.4",height:"70"}),a.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","}",":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/262f2eca63105779f30a0a5445cf76f60786039a.svg",width:"417.2",height:"50.4"}),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/0e83ebbac13a84ef6036bf4be57b3d1b6cb316f8.svg",width:"221.2",height:"49"}),a.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",a.createElement("sub",null,"1"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c87e454fb11ef7f15c7386e83ca1ce41a004d8a7.svg",width:"264.59999999999997",height:"58.8"}),a.createElement("p",null,"And after this tedious detour to find the coordinate for C",a.createElement("sub",null,"1"),", we can find C",a.createElement("sub",null,"2")," fairly simply, since it's lies at distance -C",a.createElement("sub",null,"1y")," along the end point's tangent:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/25f027074b6af8ca7b640e27636e3bf89c28afdb.svg",width:"550.1999999999999",height:"82.6"}),a.createElement("p",null,"And that's it, we have all four points now for an approximation of an arbitrary circular arc with angle \u03C6.")),a.createElement("p",null,"So, to recap, given an angle \u03C6, the new control coordinates are:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c4d82e44d1c67dda8ba26aa6da0f406d05eba618.svg",width:"215.6",height:"42"}),a.createElement("p",null,"and"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/3a4b1ee00eebb7697e5513ef9df673928913252e.svg",width:"337.4",height:"42"}),a.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 \u03C6 = \u03C0/2:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/63e0936b4849d4cdbb9a2e0909181259be951e4d.svg",width:"432.59999999999997",height:"35"}),a.createElement("p",null,"Which, in decimal values, rounded to six significant digits, is:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/fd12e65204a31319b66355c6ff99e6b3d9603b05.svg",width:"432.59999999999997",height:"16.799999999999997"}),a.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:"),a.createElement(i,{handler:e.props.handler,section:"circles_cubic",title:"Cubic B\xE9zier circle approximation",draw:e.drawCircle,dname:"drawCircle",static:!0}))}},arcapproximation:{locale:"en-GB",title:"Approximating B\xE9zier curves with circular arcs",getContent:function(e){return a.createElement("section",{className:"arcapproximation"},a.createElement(r,{name:"arcapproximation",title:"Approximating B\xE9zier curves with circular arcs",number:"43"}),a.createElement("p",null,"Let's look at doing the exact opposite of the previous section: rather than approximating circular arc using B\xE9zier curves, let's approximate B\xE9zier curves using circular arcs."),a.createElement("p",null,"We already saw in the section on circle approximation that this will never yield a perfect equivalent, but sometimes you need circular arcs, such as when you're working with fabrication machinery, or simple vector languages that understand lines and circles, but not much else."),a.createElement("p",null,"The approach is fairly simple: pick a starting point on the curve, and pick two points that are further along the curve. Determine the circle that goes through those three points, and see if it fits the part of the curve we're trying to approximate. Decent fit? Try spacing the points further apart. Bad fit? Try spacing the points closer together. Keep doing this until you've found the \"good approximation/bad approximation\" boundary, record the \"good\" arc, and then move the starting point up to overlap the end point we previously found. Rinse and repeat until we've covered the entire curve."),a.createElement("p",null,"So: step 1, how do we find a circle through three points? That part is actually really simple. You may remember (if you ever learned it!) that a line between two points on a circle is called a ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Chord_%28geometry%29"},"chord"),", and one property of chords is that the line from the center of any chord, perpendicular to that chord, passes through the center of the circle."),a.createElement("p",null,"So: if we have have three points, we have three (different) chords, and consequently, three (different) lines that go from those chords through the center of the circle. So we find the centers of the chords, find the perpendicular lines, find the intersection of those lines, and thus find the center of the circle."),a.createElement("p",null,"The following graphic shows this procedure with a different colour for each chord and its associated perpendicular through the center. You can move the points around as much as you like, those lines will always meet!"),a.createElement(i,{handler:e.props.handler,section:"arcapproximation",title:"Finding a circle through three points",setup:e.setupCircle,sname:"setupCircle",draw:e.drawCircle,dname:"drawCircle"}),a.createElement("p",null,"So, with the procedure on how to find a circle through three points, finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, over the remaining point, to the end point."),a.createElement("p",null,"So how can we convert a B\xE9zier curve into a (sequence of) circular arc(s)?"),a.createElement("ul",null,a.createElement("li",null,"Start at ",a.createElement("em",null,"t=0")),a.createElement("li",null,"Pick two points further down the curve at some value ",a.createElement("em",null,"m = t + n")," and ",a.createElement("em",null,"e = t + 2n")),a.createElement("li",null,"Find the arc that these points define"),a.createElement("li",null,"Determine how close the found arc is to the curve:",a.createElement("ul",null,a.createElement("li",null,"Pick two additional points ",a.createElement("em",null,"e1 = t + n/2")," and ",a.createElement("em",null,"e2 = t + n + n/2"),"."),a.createElement("li",null,"These points, if the arc is a good approximation of the curve interval chosen, should lie ",a.createElement("em",null,"on")," the circle, so their distance to the center of the circle should be the same as the distance from any of the three other points to the center."),a.createElement("li",null,"For point points, determine the (absolute) error between the radius of the circle, and the",a.createElement("em",null,"actual")," distance from the center of the circle to the point on the curve."),a.createElement("li",null,"If this error is too high, we consider the arc bad, and try a smaller interval.")))),a.createElement("p",null,"The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at ",a.createElement("em",null,"t=0.5"),", and then we start performing a ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Binary_search_algorithm"},"Binary Search"),"."),a.createElement("ol",null,a.createElement("li",null,"We start with ",(0,.5,1)),a.createElement("li",null,"That'll fail, so we retry with the interval halved: ",(0,.25,.5),a.createElement("ul",null,a.createElement("li",null,"If that arc's good, we move back up by half distance: ",(0,.375,.75),"."),a.createElement("li",null,"However, if the arc was still bad, we move ",a.createElement("em",null,"down")," by half the distance: ",(0,.125,.25),"."))),a.createElement("li",null,"We keep doing this over and over until we have two arcs found in sequence of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the former.")),a.createElement("p",null,"The following graphic shows the result of this approach, with a default error threshold of 0.5, meaning that if an arc is off by a ",a.createElement("em",null,"combined")," half pixel over both verification points, then we treat the arc as bad. This is an extremely simple error policy, but already works really well. Note that the graphic is still interactive, and you can use your up and down arrow keys keys to increase or decrease the error threshold, to see what the effect of a smaller or larger error threshold is."),a.createElement(i,{handler:e.props.handler,section:"arcapproximation",title:"Arc approximation of a B\xE9zier curve",setup:e.setupCubic,sname:"setupCubic",draw:e.drawSingleArc,dname:"drawSingleArc",onKeyDown:e.props.onKeyDown}),a.createElement("p",null,"With that in place, all that's left now is to \"restart\" the procedure by treating the found arc's end point as the new to-be-determined arc's starting point, and using points further down the curve. We keep trying this until the found end point is for ",a.createElement("em",null,"t=1"),", at which point we are done. Again, the following graphic allows for up and down arrow key input to increase or decrease the error threshold, so you can see how picking a different threshold changes the number of arcs that are necessary to reasonably approximate a curve:"),a.createElement(i,{handler:e.props.handler,section:"arcapproximation",title:"Arc approximation of a B\xE9zier curve",setup:e.setupCubic,sname:"setupCubic",draw:e.drawArcs,dname:"drawArcs",onKeyDown:e.props.onKeyDown}),a.createElement("p",null,"So... what is this good for? Obviously, if you're working with technologies that can't do curves, but can do lines and circles, then the answer is pretty straightforward, but what else? There are some reasons why you might need this technique: using circular arcs means you can determine whether a coordinate lies \"on\" your curve really easily (simply compute the distance to each circular arc center, and if any of those are close to the arc radii, at an angle between the arc start and end, bingo, this point can be treated as lying \"on the curve\"). Another benefit is that this approximation is \"linear\": you can almost trivially travel along the arcs at fixed speed. You can also trivially compute the arc length of the approximated curve (it's a bit like curve flattening). The only thing to bear in mind is that this is a lossy equivalence: things that you compute based on the approximation are guaranteed \"off\" by some small value, and depending on how much precision you need, arc approximation is either going to be super useful, or completely useless. It's up to you to decide which, based on your application!"))}},bsplines:{locale:"en-GB",title:"B-Splines",getContent:function(e){return a.createElement("section",{className:"bsplines"},a.createElement(r,{name:"bsplines",title:"B-Splines",number:"44"}),a.createElement("p",null,"No discussion on B\xE9zier curves is complete without also giving mention of that other beast in the curve design space: B-Splines. Easily confused to mean B\xE9zier splines, that's not actually what they are; they are \"basis function\" splines, which makes a lot of difference, and we'll be looking at those differences in this section. We're not going to dive as deep into B-Splines as we have for B\xE9zier curves (that would be an entire primer on its own) but we'll be looking at how B-Splines work, what kind of maths is involved in computing them, and how to draw them based on a number of parameters that you can pick for individual B-Splines."),a.createElement("p",null,"First off: B-Splines are ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Piecewise"},"piecewise polynomial interpolation curves"),", where the \"single curve\" is built by performing polynomial interpolation over a set of points, using a sliding window of a fixed number of points. For instance, a \"cubic\" B-Spline defined by twelve points will have its curve built by evaluating the polynomial interpolation of four points, and the curve can be treated as a lot of different sections, each controlled by four points at a time, such that the full curve consists of smoothly connected sections defined by points ","{","1,2,3,4","}",", ","{","2,3,4,5","}",", ..., ","{","8,9,10,11","}",", and finally ","{","9,10,11,12","}",", for eight sections."),a.createElement("p",null,"What do they look like? They look like this! .. okay that's an empty graph, but simply click to place some point, with the stipulation that you need at least four point to see any curve. More than four points simply draws a longer B-Spline curve:"),a.createElement(o,{sketch:e.basicSketch}),a.createElement("p",null,"The important part to notice here is that we are ",a.createElement("strong",null,"not")," doing the same thing with B-Splines that we do for poly-B\xE9ziers or Catmull-Rom curves: both of the latter simply define new sections as literally \"new sections based on new points\", so a 12 point cubic poly-B\xE9zier curve is actually impossible, because we start with a four point curve, and then add three more points for each section that follows, so we can only have 4, 7, 10, 13, 16, etc point Poly-B\xE9ziers. Similarly, while Catmull-Rom curves can grow by adding single points, this addition of a single point introduces three implicit B\xE9zier points. Cubic B-Splines, on the other hand, are smooth interpolations of ",a.createElement("em",null,"each possible curve involving four consecutive points"),", such that at any point along the curve except for our start and end points, our on-curve coordinate is defined by four control points."),a.createElement("p",null,"Consider the difference to be this:"),a.createElement("ul",null,a.createElement("li",null,"for B\xE9zier curves, the curve is defined as an interpolation of points, but:"),a.createElement("li",null,"for B-Splines, the curve is defined as an interpolation of ",a.createElement("em",null,"curves"),".")),a.createElement("p",null,"In order to make this interpolation of curves work, the maths is necessarily more complex than the maths for B\xE9zier curves, so let's have a look at how things work."),a.createElement("h2",{id:"how-to-compute-a-b-spline-curve-some-maths"},"How to compute a B-Spline curve: some maths"),a.createElement("p",null,"Given a B-Spline of degree ",a.createElement("code",null,"d")," and thus order ",a.createElement("code",null,"k=d+1")," (so a quadratic B-Spline is degree 2 and order 3, a cubic B-Spline is degree 3 and order 4, etc) and ",a.createElement("code",null,"n")," control points ",a.createElement("code",null,"P",a.createElement("sub",null,"0"))," through ",a.createElement("code",null,"P",a.createElement("sub",null,"n-1")),", we can compute a point on the curve for some value ",a.createElement("code",null,"t")," in the interval [0,1] (where 0 is the start of the curve, and 1 the end, just like for B\xE9zier curves), by evaluating the following function:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/329da80e737b0005f4dbe4c84ff868bde5dfaee0.svg",width:"177.79999999999998",height:"43.4"}),a.createElement("p",null,"Which, honestly, doesn't tell us all that much. All we can see is that a point on a B-Spline curve is defined as \"a mix of all the control points, weighted somehow\", where the weighting is achieved through the ",a.createElement("em",null,"N(...)")," function, subscripted with an obvious parameter ",a.createElement("code",null,"i"),", which comes from our summation, and some magical parameter ",a.createElement("code",null,"k"),". So we need to know two things: 1. what does N(t) do, and 2. what is that ",a.createElement("code",null,"k"),"? Let's cover both, in reverse order."),a.createElement("p",null,"The parameter ",a.createElement("code",null,"k")," represents the \"knot interval\" over which a section of curve is defined. As we learned earlier, a B-Spline curve is itself an interpoliation of curves, and we can treat each transition where a control point starts or stops influencing the total curvature as a \"knot on the curve\". Doing so for a degree ",a.createElement("code",null,"d")," B-Spline with ",a.createElement("code",null,"n")," control point gives us ",a.createElement("code",null,"d + n + 1")," knots, defining ",a.createElement("code",null,"d + n")," intervals along the curve, and it is these intervals that the above ",a.createElement("code",null,"k")," subscript to the N() function applies to."),a.createElement("p",null,"Then the N() function itself. What does it look like?"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/c10575fb591062784484357356796a4c0be4f83e.svg",width:"586.5999999999999",height:"44.8"}),a.createElement("p",null,"So this is where we see the interpolation: N(t) for an (i,k) pair (that is, for a step in the above summation, on a specific knot interval) is a mix between N(t) for (i,k-1) and N(t) for (i+1,k-1), so we see that this is a recursive iteration where ",a.createElement("code",null,"i")," goes up, and ",a.createElement("code",null,"k")," goes down, so it seem reasonable to expect that this recursion has to stop at some point; obviously, it does, and specifically it does so for the following ",a.createElement("code",null,"i"),"/",a.createElement("code",null,"k")," values:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/6664a4fc5832059bbc68eaa8068a4b2577e1d96a.svg",width:"251.99999999999997",height:"42"}),a.createElement("p",null,"And this function finally has a straight up evaluation: if a ",a.createElement("code",null,"t")," value lies within a knot-specific interval once we reach a ",a.createElement("code",null,"k=1")," value, it \"counts\", otherwise it doesn't. We did cheat a little, though, because for all these values we need to scale our ",a.createElement("code",null,"t")," value first, so that it lies in the interval bounded by ",a.createElement("code",null,"knots[d]")," and ",a.createElement("code",null,"knots[n]"),", which are the start point and end point where curvature is controlled by exactly ",a.createElement("code",null,"order")," control points. For instance, for degree 3 (=order 4) and 7 control points, with knot vector [1,2,3,4,5,6,7,8,9,10,11], we map ",a.createElement("code",null,"t")," from [the interval 0,1] to the interval [4,8], and then use that value in the functions above, instead."),a.createElement("h2",{id:"can-we-simplify-that-"},"Can we simplify that?"),a.createElement("p",null,"We can, yes."),a.createElement("p",null,"People far smarter than us have looked at this work, and two in particular \u2014 ",a.createElement("a",{href:"http://www.npl.co.uk/people/maurice-cox"},"Maurice Cox")," and ",a.createElement("a",{href:"https://en.wikipedia.org/wiki/Carl_R._de_Boor"},"Carl de Boor")," \u2014 came to a mathematically pleasing solution: to compute a point P(t), we can compute this point by evaluating ",a.createElement("em",null,"d(t)")," on a curve section between knots ",a.createElement("em",null,"i")," and ",a.createElement("em",null,"i+1"),":"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/3780a420cd9b1bc59bec2c49bbd29f5e58497a3c.svg",width:"295.4",height:"22.4"}),a.createElement("p",null,"This is another recursive function, with ",a.createElement("em",null,"k")," values decreasing from the curve order to 1, and the value ",a.createElement("em",null,"\u03B1")," (alpha) defined by:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/ba3b25cd54993b4601d8f415bc4cde73af4fc460.svg",width:"267.4",height:"40.599999999999994"}),a.createElement("p",null,"That looks complicated, but it's not. Computing alpha is just a fraction involving known, plain numbers and once we have our alpha value, computing (1-alpha) is literally just \"computing one minus alpha\". Computing this d() function is thus simply a matter of \"computing simple arithmetics but with recursion\", which might be computationally expensive because we're doing \"a lot of\" steps, but is also computationally cheap because each step only involves very simple maths. Of course as before the recursion has to stop:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/1405067abebab73574934e3e69d7a7158106c744.svg",width:"386.4",height:"42"}),a.createElement("p",null,"So, we see two stopping conditions: either ",a.createElement("code",null,"i")," becomes 0, in which case d() is zero, or ",a.createElement("code",null,"k")," becomes zero, in which case we get the same \"either 1 or 0\" that we saw in the N() function above."),a.createElement("p",null,"Thanks to Cox and de Boor, we can compute points on a B-Spline pretty easily: we just need to compute a triangle of interconnected values. For instance, d() for i=3, k=3 yields the following triangle:"),a.createElement("img",{className:"LaTeX SVG",src:"images/latex/a0a1069b001c75a1fab7f40ffa8bc403e1408f0d.svg",width:"438.2",height:"242.2"}),a.createElement("p",null,"That is, we compute d(3,3) as a mixture of d(2,3) and d(2,2): d(3,3) = a(3,3) x d(2,3) + (1-a(3,3)) x d(2,2)... and we simply keep expanding our triangle until we reach the terminating function parameters. Done deal!"),a.createElement("p",null,"One thing we need to keep in mind is that we're working with a spline that is constrained by its control points, so even though the ",a.createElement("code",null,"d(..., k)")," values are zero or one at the lowest level, they are really \"zero or one, times their respective control point\", so in the next section you'll see the algorithm for running through the computation in a way that starts with a copy of the control point vector and then works its way up to that single point: that's pretty essential!"),a.createElement("p",null,"If we run this computation \"down\", starting at d(3,3), then without special code in place we would be computing quite a few terms multiple times at each step. On the other hand, we can also start with that last \"column\", we can generate the terminating d() values first, then compute the a() constants, perform our multiplications, generate the previous step's d() values, compute their a() constants, do the multiplications, etc. until we end up all the way back at the top. If we run our computation this way, we don't need any explicit caching, we can just \"recycle\" the list of numbers we start with and simply update them as we move up the triangle. So, let's implement that!"),a.createElement("h2",{id:"cool-cool-but-i-don-t-know-what-to-do-with-that-information"},"Cool, cool... but I don't know what to do with that information"),a.createElement("p",null,"I know, this is pretty mathy, so let's have a look at what happens when we change parameters here. We can't change the maths for the interpolation functions, so that gives us only one way to control what happens here: the knot vector itself. As such, let's look at the graph that shows the interpolation functions for a cubic B-Spline with seven points with a uniform knot vector (so we see seven identical functions), representing how much each point (represented by one function each) influences the total curvature, given our knot values. And, because exploration is the key to discovery, let's make the knot vector a thing we can actually manipulate. Normally a proper knot vector has a constraint that any value is strictly equal to, or larger than the previous ones, but screw it this is programming, let's ignore that hard restriction and just mess with the knots however we like."),a.createElement("div",{className:"two-column"},a.createElement(s,{ref:"interpolation-graph"}),a.createElement(o,{sketch:e.interpolationGraph,controller:function(t,n){return e.bindKnots(t,n,"interpolation-graph")}})),a.createElement("p",null,"Changing the values in the knot vector changes how much each point influences the total curvature (with some clever knot value manipulation, we can even make the influence of certain points disappear entirely!), so we can see that while the control points define the hull inside of which we're going to be drawing a curve, it is actually the knot vector that determines the actual ",a.createElement("em",null,"shape")," of the curve inside that hull."),a.createElement("p",null,"After reading the rest of this section you may want to come back here to try some specific knot vectors, and see if the resulting interpolation landscape makes sense given what you will now think should happen!"),a.createElement("h2",{id:"running-the-computation"},"Running the computation"),a.createElement("p",null,"Unlike the de Casteljau algorithm, where the ",a.createElement("code",null,"t")," value stays the same at every iteration, for B-Splines that is not the case, and so we end having to (for each point we evaluate) run a fairly involving bit of recursive computation. The algorithm is discussed on ",a.createElement("a",{href:"http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/de-Boor.html"},"this Michigan Tech")," page, but an easier to read version is implemented by ",a.createElement("a",{href:"https://github.com/thibauts/b-spline/blob/master/index.js#L59-L71"},"b-spline.js"),", so we'll look at its code."),a.createElement("p",null,"Given an input value ",a.createElement("code",null,"t"),", we first map the input to a value from the domain [0,1] to the domain [knots[degree], knots[knots.length - 1 - degree]. Then, we find the section number ",a.createElement("code",null,"s")," that this mapped ",a.createElement("code",null,"t")," value lies on:"),a.createElement("pre",null,"for(s=domain[0]; s < domain[1]; s++) {\n if(knots[s] <= t && t <= knots[s+1]) break;\n}\n"),a.createElement("p",null,"after running this code, ",a.createElement("code",null,"s")," is the index for the section the point will lie on. We then run the algorithm mentioned on the MU page (updated to use this description's variable names):"),a.createElement("pre",null,"let v = copy of control points\n\nfor(let L = 1; L <= order; L++) {\n for(let i=s; i > 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}\n"),a.createElement("p",null,"(A nice bit of behaviour in this code is that we work the interpolation \"backwards\", starting at ",a.createElement("code",null,"i=s")," at each level of the interpolation, and we stop when ",a.createElement("code",null,"i = s - order + level"),", so we always end up with a value for ",a.createElement("code",null,"i")," such that those ",a.createElement("code",null,"v[i-1]")," don't try to use an array index that doesn't exist)"),a.createElement("h2",{id:"open-vs-closed-paths"},"Open vs. closed paths"),a.createElement("p",null,"Much like poly-B\xE9ziers, B-Splines can be either open, running from the first point to the last point, or closed, where the first and last point are ",a.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 ",a.createElement("code",null,"d")," B-Spline, we need to make the last ",a.createElement("code",null,"d")," point the same as the first ",a.createElement("code",null,"d")," points. And the easiest way to do this is to simply append ",a.createElement("code",null,"points.splice(0,d)")," to ",a.createElement("code",null,"points"),". Done!"),a.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 ",a.createElement("code",null,"points[0]")," and ",a.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."),a.createElement("h2",{id:"manipulating-the-curve-through-the-knot-vector"},"Manipulating the curve through the knot vector"),a.createElement("p",null,"The most important thing to understand when it comes to B-Splines is that they work ",a.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 ",a.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:"),a.createElement("ol",null,a.createElement("li",null,"we can use a uniform knot vector, with equally spaced intervals,"),a.createElement("li",null,"we can use a non-uniform knot vector, without enforcing equally spaced intervals,"),a.createElement("li",null,"we can collapse sequential knots to the same value, locally lowering curve complexity using \"null\" intervals, and"),a.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.")),a.createElement("h3",{id:"uniform-b-splines"},"Uniform B-Splines"),a.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 ",a.createElement("em",null,"the same intervals"),", or even [0,2,3,...,18,20,22], which also defines ",a.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."),a.createElement("div",{className:"two-column"},a.createElement(s,{ref:"uniform-spline"}),a.createElement(o,{sketch:e.uniformBSpline,controller:function(t,n){return e.bindKnots(t,n,"uniform-spline")}})),a.createElement("p",null,"This is an important point: the intervals that the knot vector defines are ",a.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."),a.createElement("p",null,"The problem with uniform knot vectors is that, as we need ",a.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..."),a.createElement("h3",{id:"reducing-local-curve-complexity-by-collapsing-intervals"},"Reducing local curve complexity by collapsing intervals"),a.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 every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing ",a.createElement("code",null,"order")," knots creates a situation where all continuity is lost and the curve \"kinks\"."),a.createElement("div",{className:"two-column"},a.createElement(s,{ref:"center-cut-bspline"}),a.createElement(o,{sketch:e.centerCutBSpline,controller:function(t,n){return e.bindKnots(t,n,"center-cut-bspline")}})),a.createElement("h3",{id:"open-uniform-b-splines"},"Open-Uniform B-Splines"),a.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:"),a.createElement("p",null,"For any curve of degree ",a.createElement("code",null,"D")," with control points ",a.createElement("code",null,"N"),", we can define a knot vector of length ",a.createElement("code",null,"N+D+1")," in which the values ",a.createElement("code",null,"0 ... D+1")," are the same, the values ",a.createElement("code",null,"D+1 ... N+1")," follow the \"uniform\" pattern, and the values ",a.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."),a.createElement("div",{className:"two-column"},a.createElement(s,{ref:"open-uniform-bspline"}),a.createElement(o,{sketch:e.openUniformBSpline,controller:function(t,n){return e.bindKnots(t,n,"open-uniform-bspline")}})),a.createElement("h3",{id:"non-uniform-b-splines"},"Non-uniform B-Splines"),a.createElement("p",null,"This is essentially 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 ",a.createElement("code",null,"knots[k+1]")," should be equal to, or greater than ",a.createElement("code",null,"knots[k]"),"."),a.createElement("h2",{id:"one-last-thing-rational-b-splines"},"One last thing: Rational B-Splines"),a.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."),a.createElement("div",{className:"two-column"},a.createElement(d,{ref:"rational-uniform-bspline-weights"}),a.createElement(o,{scrolling:!0,sketch:e.rationalUniformBSpline,controller:function(t,n,a,i){e.bindWeights(t,a,i,"rational-uniform-bspline-weights")}})),a.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."),a.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."),a.createElement("h2",{id:"extending-our-implementation-to-cover-rational-splines"},"Extending our implementation to cover rational splines"),a.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."),a.createElement("p",null,"For example, a 2D point ",a.createElement("code",null,"(x,y)")," with weight ",a.createElement("code",null,"w")," becomes a 3D point ",a.createElement("code",null,"(w * x, w * y, w)"),"."),a.createElement("p",null,"We then run the same algorithm as before, which will automatically 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."),a.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 ",a.createElement("code",null,"w'")," and divide all the regular coordinate dimensions by it, then throw away the weight information."),a.createElement("p",null,"Based on our previous example, we take the final 3D point ",a.createElement("code",null,"(x', y', w')"),", which we then turn back into a 2D point by computing ",a.createElement("code",null,"(x'/w', y'/w')"),". And that's it, we're done!"))}},comments:{locale:"en-GB",title:"Comments and questions",getContent:function(){return a.createElement("section",{className:"comments"},a.createElement("script",null,"/* ----------------------------------------------------------------------------- * * * PLEASE DO NOT LOCALISE THIS FILE * * I can't respond to questions that aren't asked in English, so this is one of * the few cases where there is a content.en-GB.md but you shouldn't change it. * * ----------------------------------------------------------------------------- */"),a.createElement(r,{name:"comments",title:"Comments and questions",number:"45"}),a.createElement("p",null,"First off, 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 have two options: you can either head on over to the ",a.createElement("a",{href:"https://patreon.com/bezierinfo"},"Patreon page")," for this book, or if you prefer to make a one-time donation, head on over to the ",a.createElement("a",{href:"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QPRDLNGDANJSW"},"buy Pomax a coffee")," page. This work has grown from a small primer to a 70-plus print-page-equivalent reader on the subject of B\xE9zier curves over the years, 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."),a.createElement("p",null,"With that said, on to the comments!"),a.createElement("div",{id:"disqus_thread"}))}},"locale-switcher":{locale:"en-GB",title:"locale-switcher",getContent:function(){return a.createElement("section",null,a.createElement("p",null,"Read this in your own language:"),a.createElement("ul",null,a.createElement("li",null,a.createElement("a",{href:"./en-GB"},"English")),a.createElement("li",null,a.createElement("a",{href:"./ja-JP"},"\u65E5\u672C\u8A9E")),a.createElement("li",null,a.createElement("a",{href:"./zh-CN"},"\u4E2D\u6587"))),a.createElement("p",null,"Don't see your language listed? ",a.createElement("a",{href:"https://github.com/Pomax/BezierInfo-2/wiki/localize"},"Help translate this content!")))}}}},function(e,t,n){"use strict";var a=n(6),i=n(56),r=new i,o="locale-switcher";e.exports=function(){return a.createElement("div",{className:o},r.getContent(o,this))}},function(e,t,n){"use strict";e.exports={LocaleSwitcher:n(205)}},function(e){e.exports={"June 2020":["Added automatic CI/CD via Github Actions"],"January 2020":["Added reset buttons to all graphics","Updated to preface to correctly describe the on-page maths","Fixed the Catmull-Rom section because it had glaring maths errors"],"August 2019":["Added a section on (plain) rational Bezier curves","Improved the Graphic component to allow for sliders"],"December 2018":["Added a section on curvature and calculating kappa.","Added a Patreon page! Head on over to https://patreon.com/bezierinfo to help support this site!"],"August 2018":["Added a section on finding a curve's y, if all you have is the x coordinate."],"July 2018":["Rewrote the 3D normals section, implementing and explaining Rotation Minimising Frames.","Updated the section on curve order raising/lowering, showing how to get a least-squares optimized lower order curve.","(Finally) updated 'npm test' so that it automatically rebuilds when files are changed while the dev server is running."],"June 2018":["Added a section on direct curve fitting.","Added source links for all graphics.","Added this \"What's new?\" section."],"April 2017":["Added a section on 3d normals.","Added live-updating for the social link buttons, so they always link to the specific section you're reading."],"February 2017":["Finished rewriting the entire codebase for localization."],"January 2016":["Added a section to explain the Bezier interval."],"December 2015":["Set up the split repository between BezierInfo-2 as development repository, and bezierinfo as live page.","Removed the need for client-side LaTeX parsing entirely, so the site doesn't take a full minute or more to load all the graphics."],"May 2015":["Switched over to pure JS rather than Processing-through-Processing.js","Added Cardano's algorithm for finding the roots of a cubic polynomial."],"April 2015":["Added a section on arc length approximations."],"February 2015":["Added a section on the canonical cubic Bezier form."],"November 2014":["Switched to HTTPS."],"July 2014":["Added the section on arc approximation."],"April 2014":["Added the section on Catmull-Rom fitting."],"November 2013":["Added the section on Catmull-Rom / Bezier conversion.","Added the section on Bezier cuves as matrices"],"April 2013":["Added a section on poly-Beziers.","Added a section on boolean shape operations."],"March 2013":["First drastic rewrite","Added sections on circle approximations.","Added a section on projecting a point onto a curve.","Added a section on tangents and normals.","Added Legendre-Gauss numerical data tables."],"October 2011":["First commit for the https://pomax.github.io/bezierinfo site, based on the pre-Primer webpage that covered the basics of Bezier curves in HTML with Processing.js examples."]}},function(e,t,n){"use strict";var a=n(6),i=n(207),r=a.createClass({displayName:"Changelog",getInitialState:function(){return{showContent:!1}},getContent:function(){var e=Object.keys(i);return e.map(function(e){return a.createElement("div",{className:"period"},a.createElement("h3",null,e),a.createElement("ul",{className:"changes"},i[e].map(function(e){return a.createElement("li",null,e)})))})},toggle:function(){console.log("setting state"),this.setState({showContent:!this.state.showContent})},render:function(){var e="";return this.state.showContent&&(e=this.getContent()),a.createElement("section",{className:"whats-new"},a.createElement("h2",null,"What's new?"),a.createElement("p",null,"This primer is a living document, and so depending on when you last look at it, there may be new content. Click the following link to expand this section to have a look at what got added, when."),a.createElement("p",{className:"click-me",onClick:this.toggle},"Click here to ",this.state.showContent?"hide":"view"," the change log."),a.createElement("div",null,e))}});e.exports=r},function(e,t,n){"use strict";var a=n(6),i=a.createClass({displayName:"Header",render:function(){return a.createElement("header",null,a.createElement("h1",null,"A Primer on B\xE9zier Curves"),a.createElement("h2",null,"A free, online book for when you really need to know how to do B\xE9zier things."),a.createElement("h4",{className:"support"},"(want to help support the book? Head on over to the ",a.createElement("a",{className:"support-link",href:"https://patreon.com/bezierinfo"},"Patreon page"),"!)"))}});e.exports=i},function(e,t,n){"use strict";var a=n(6),i=a.createClass({displayName:"Ribbon",getInitialState:function(){return{href:"http://github.com/pomax/BezierInfo-2"}},render:function(){return a.createElement("div",{className:"ribbon"},a.createElement("img",{src:"images/ribbon.png",alt:"This page on GitHub",style:{border:"none"},useMap:"#githubmap",width:"200",height:"149"}),a.createElement("map",{name:"githubmap"},a.createElement("area",{shape:"poly",coords:"30,0, 200,0, 200,114",href:this.state.href,alt:"This page on GitHub"})))}});e.exports=i},function(e,t,n){"use strict";var a=n(6),i=n(210),r=n(209),o=n(208),s=n(206).LocaleSwitcher,d=n(186),l=n(89),c=a.createClass({displayName:"Page",render:function(){return a.createElement("div",null,a.createElement(i,null),a.createElement(r,null),this.renderPageContent(),a.createElement(l,null))},renderPageContent:function(){return a.createElement("div",null,a.createElement(s,null),a.createElement(d,null),a.createElement(o,null),this.props.children)}});e.exports=c},function(e,t,n){"use strict";var a=n(6),i=n(211),r=n(52),o=function(e){return Object.keys(r).map(e)}(function(e,t){var n=r[e];return a.createElement(n,{key:e,name:e,number:t})}),s=a.createClass({displayName:"FullArticle",render:function(){return a.createElement(i,null,o)}});e.exports=s},function(e,t,n){"use strict";var a=n(58);e.exports=a.renderSubtreeIntoContainer},function(e,t,n){"use strict";var a=n(2),i=n(13),r=n(4),o=n(20),s=n(57),d=n(1),l=n(3);e.exports=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=o.get(e);return t?(t=s(t),t?r.getNodeFromInstance(t):null):void("function"==typeof e.render?a("44"):a("45",Object.keys(e)))}},function(e){"use strict";e.exports="15.6.2"},function(e){"use strict";e.exports=function(e){for(var t=1,r=0,o=0,s=e.length,l=-4&s;o/,r=/^<\!\-\-/,o={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=a(e);return r.test(e)?e:e.replace(i," "+o.CHECKSUM_ATTR_NAME+"=\""+t+"\"$&")},canReuseMarkup:function(e,t){var n=t.getAttribute(o.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=a(e);return i===n}};e.exports=o},function(e){"use strict";e.exports={useCreateElement:!0,useFiber:!1}},function(e,t,n){"use strict";var a=n(34);e.exports=function(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?9===t.nodeType?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return!1,n}},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(29);i.augmentClass(a,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null}),e.exports=a},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(11);i.augmentClass(a,{propertyName:null,elapsedTime:null,pseudoElement:null}),e.exports=a},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(21),r=n(44);i.augmentClass(a,{touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:r}),e.exports=a},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(29);i.augmentClass(a,{dataTransfer:null}),e.exports=a},function(e,t,n){"use strict";var i=n(33),r={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},o={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=function(e){if(e.key){var t=r[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=i(e);return 13===n?"Enter":a(n)}return"keydown"===e.type||"keyup"===e.type?o[e.keyCode]||"Unidentified":""}},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(21),r=n(33),o=n(224),s=n(44);i.augmentClass(a,{key:o,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?r(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?r(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),e.exports=a},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(21);i.augmentClass(a,{relatedTarget:null}),e.exports=a},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(11);i.augmentClass(a,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),e.exports=a},function(e,t,n){"use strict";function a(e,t,n,a){return i.call(this,e,t,n,a)}var i=n(11);i.augmentClass(a,{animationName:null,elapsedTime:null,pseudoElement:null}),e.exports=a},function(e,t,n){"use strict";function a(e){return"."+e._rootNodeID}function i(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}var r=n(2),o=n(61),s=n(23),d=n(4),l=n(228),c=n(227),u=n(11),h=n(226),p=n(225),m=n(29),g=n(223),f=n(222),w=n(221),y=n(21),v=n(220),b=n(12),x=n(33),_=n(1),E={},C={};["abort","animationEnd","animationIteration","animationStart","blur","canPlay","canPlayThrough","click","contextMenu","copy","cut","doubleClick","drag","dragEnd","dragEnter","dragExit","dragLeave","dragOver","dragStart","drop","durationChange","emptied","encrypted","ended","error","focus","input","invalid","keyDown","keyPress","keyUp","load","loadedData","loadedMetadata","loadStart","mouseDown","mouseMove","mouseOut","mouseOver","mouseUp","paste","pause","play","playing","progress","rateChange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeUpdate","touchCancel","touchEnd","touchMove","touchStart","transitionEnd","volumeChange","waiting","wheel"].forEach(function(e){var t=e[0].toUpperCase()+e.slice(1),n="on"+t,a="top"+t,i={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[a]};E[e]=i,C[a]=i});var k={};e.exports={eventTypes:E,extractEvents:function(e,t,n,a){var i=C[e];if(!i)return null;var o;switch(e){case"topAbort":case"topCanPlay":case"topCanPlayThrough":case"topDurationChange":case"topEmptied":case"topEncrypted":case"topEnded":case"topError":case"topInput":case"topInvalid":case"topLoad":case"topLoadedData":case"topLoadedMetadata":case"topLoadStart":case"topPause":case"topPlay":case"topPlaying":case"topProgress":case"topRateChange":case"topReset":case"topSeeked":case"topSeeking":case"topStalled":case"topSubmit":case"topSuspend":case"topTimeUpdate":case"topVolumeChange":case"topWaiting":o=u;break;case"topKeyPress":if(0===x(n))return null;case"topKeyDown":case"topKeyUp":o=p;break;case"topBlur":case"topFocus":o=h;break;case"topClick":if(2===n.button)return null;case"topDoubleClick":case"topMouseDown":case"topMouseMove":case"topMouseUp":case"topMouseOut":case"topMouseOver":case"topContextMenu":o=m;break;case"topDrag":case"topDragEnd":case"topDragEnter":case"topDragExit":case"topDragLeave":case"topDragOver":case"topDragStart":case"topDrop":o=g;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":o=f;break;case"topAnimationEnd":case"topAnimationIteration":case"topAnimationStart":o=l;break;case"topTransitionEnd":o=w;break;case"topScroll":o=y;break;case"topWheel":o=v;break;case"topCopy":case"topCut":case"topPaste":o=c;}o||!1?void 0:r("86",e);var d=o.getPooled(i,t,n,a);return s.accumulateTwoPhaseDispatches(d),d},didPutListener:function(e,t){if("onClick"===t&&!i(e._tag)){var n=a(e),r=d.getNodeFromInstance(e);k[n]||(k[n]=o.listen(r,"click",b))}},willDeleteListener:function(e,t){if("onClick"===t&&!i(e._tag)){var n=a(e);k[n].remove(),delete k[n]}}}},function(e,t,n){"use strict";function a(e){if("selectionStart"in e&&d.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function i(e,t){if(y||null==g||g!==c())return null;var n=a(g);if(!w||!h(w,n)){w=n;var i=l.getPooled(m.select,f,e,t);return i.type="select",i.target=g,r.accumulateTwoPhaseDispatches(i),i}return null}var r=n(23),o=n(7),s=n(4),d=n(60),l=n(11),c=n(59),u=n(76),h=n(38),p=o.canUseDOM&&"documentMode"in document&&11>=document.documentMode,m={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:["topBlur","topContextMenu","topFocus","topKeyDown","topKeyUp","topMouseDown","topMouseUp","topSelectionChange"]}},g=null,f=null,w=null,y=!1,v=!1;e.exports={eventTypes:m,extractEvents:function(e,t,n,a){if(!v)return null;var r=t?s.getNodeFromInstance(t):window;switch(e){case"topFocus":(u(r)||"true"===r.contentEditable)&&(g=r,f=t,w=null);break;case"topBlur":g=null,f=null,w=null;break;case"topMouseDown":y=!0;break;case"topContextMenu":case"topMouseUp":return y=!1,i(n,a);case"topSelectionChange":if(p)break;case"topKeyDown":case"topKeyUp":return i(n,a);}return null},didPutListener:function(e,t){"onSelect"===t&&(v=!0)}}},function(e){"use strict";var t={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},n={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlns:0,xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},a={Properties:{},DOMAttributeNamespaces:{xlinkActuate:t.xlink,xlinkArcrole:t.xlink,xlinkHref:t.xlink,xlinkRole:t.xlink,xlinkShow:t.xlink,xlinkTitle:t.xlink,xlinkType:t.xlink,xmlBase:t.xml,xmlLang:t.xml,xmlSpace:t.xml},DOMAttributeNames:{}};Object.keys(n).forEach(function(e){a.Properties[e]=0,n[e]&&(a.DOMAttributeNames[e]=n[e])}),e.exports=a},function(e){"use strict";e.exports=function(e){var t=e?e.ownerDocument||e:document,n=t.defaultView||window;return!!(e&&("function"==typeof n.Node?e instanceof n.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}},function(e,t,n){"use strict";var a=n(232);e.exports=function(e){return a(e)&&3==e.nodeType}},function(e,t,n){"use strict";function a(e,t){return!!(e&&t)&&(e===t||!i(e)&&(i(t)?a(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var i=n(233);e.exports=a},function(e){"use strict";function t(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function n(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}e.exports=function(e,a){for(var i=t(e),r=0,o=0;i;){if(3===i.nodeType){if(o=r+i.textContent.length,r<=a&&o>=a)return{node:i,offset:a-r};r=o}i=t(n(i))}}},function(e,t,n){"use strict";function a(e,t,n,a){return e===n&&t===a}var i=n(7),r=n(235),o=n(80),s=i.canUseDOM&&"selection"in document&&!("getSelection"in window),l={getOffsets:s?function(e){var t=document.selection,n=t.createRange(),a=n.text.length,i=n.duplicate();i.moveToElementText(e),i.setEndPoint("EndToStart",n);var r=i.text.length;return{start:r,end:r+a}}:function(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,i=t.anchorOffset,r=t.focusNode,o=t.focusOffset,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(t){return null}var d=a(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=d?0:s.toString().length,c=s.cloneRange();c.selectNodeContents(e),c.setEnd(s.startContainer,s.startOffset);var u=a(c.startContainer,c.startOffset,c.endContainer,c.endOffset),h=u?0:c.toString().length,p=h+l,m=document.createRange();m.setStart(n,i),m.setEnd(r,o);var g=m.collapsed;return{start:g?p:h,end:g?h:p}},setOffsets:s?function(e,t){var n=document.selection.createRange().duplicate(),a,i;t.end===void 0?(a=t.start,i=a):t.start>t.end?(a=t.end,i=t.start):(a=t.start,i=t.end),n.moveToElementText(e),n.moveStart("character",a),n.setEndPoint("EndToStart",n),n.moveEnd("character",i-a),n.select()}:function(e,t){if(window.getSelection){var n=window.getSelection(),a=e[o()].length,i=d(t.start,a),s=void 0===t.end?i:d(t.end,a);if(!n.extend&&i>s){var l=s;s=i,i=l}var c=r(e,i),u=r(e,s);if(c&&u){var h=document.createRange();h.setStart(c.node,c.offset),n.removeAllRanges(),i>s?(n.addRange(h),n.extend(u.node,u.offset)):(h.setEnd(u.node,u.offset),n.addRange(h))}}}};e.exports=l},function(e,t,n){"use strict";function a(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.useCreateElement=e}var i=n(5),r=n(79),o=n(14),s=n(26),d=n(60),l=n(8),c=n(30),u=n(35),h={initialize:d.getSelectionInformation,close:d.restoreSelection},p=[h,{initialize:function(){var e=s.isEnabled();return s.setEnabled(!1),e},close:function(e){s.setEnabled(e)}},{initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}}];i(a.prototype,c,{getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getUpdateQueue:function(){return u},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(e){this.reactMountReady.rollback(e)},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null}}),o.addPoolingTo(a),e.exports=a},function(e,t,n){"use strict";var a=n(17),i=n(22),r=n(48),o=n(39),s=n(65),d=n(26),l=n(64),c=n(9),u={Component:o.injection,DOMProperty:a.injection,EmptyComponent:s.injection,EventPluginHub:i.injection,EventPluginUtils:r.injection,EventEmitter:d.injection,HostComponent:l.injection,Updates:c.injection};e.exports=u},function(e){"use strict";e.exports=function(e){return e.Window&&e instanceof e.Window?{x:e.pageXOffset||e.document.documentElement.scrollLeft,y:e.pageYOffset||e.document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}},function(e,t,n){"use strict";function a(e){for(;e._hostParent;)e=e._hostParent;var t=u.getNodeFromInstance(e),n=t.parentNode;return u.getClosestInstanceFromNode(n)}function i(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function r(e){var t=p(e.nativeEvent),n=u.getClosestInstanceFromNode(t),r=n;do e.ancestors.push(r),r=r&&a(r);while(r);for(var o=0;o"+p+""},receiveComponent:function(e){if(e!==this._currentElement){this._currentElement=e;var t=""+e;if(t!==this._stringText){this._stringText=t;var n=this.getHostNode();r.replaceDelimitedText(n[0],n[1],t)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=s.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n&&1?a("67",this._domID):void 0,8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._hostNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,s.uncacheNode(this)}}),e.exports=u},function(e,t,n){"use strict";function a(e,t){"_hostNode"in e||!1?void 0:o("33"),"_hostNode"in t||!1?void 0:o("33");for(var n=0,a=e;a;a=a._hostParent)n++;for(var i=0,r=t;r;r=r._hostParent)i++;for(;0"},receiveComponent:function(){},getHostNode:function(){return r.getNodeFromInstance(this)},unmountComponent:function(){r.uncacheNode(this)}}),e.exports=o},function(e,t,n){"use strict";function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(){}var r=n(35),o=n(3),s=function(){function e(t){a(this,e),this.transaction=t}return e.prototype.isMounted=function(){return!1},e.prototype.enqueueCallback=function(e,t,n){this.transaction.isInTransaction()&&r.enqueueCallback(e,t,n)},e.prototype.enqueueForceUpdate=function(e){this.transaction.isInTransaction()?r.enqueueForceUpdate(e):i(e,"forceUpdate")},e.prototype.enqueueReplaceState=function(e,t){this.transaction.isInTransaction()?r.enqueueReplaceState(e,t):i(e,"replaceState")},e.prototype.enqueueSetState=function(e,t){this.transaction.isInTransaction()?r.enqueueSetState(e,t):i(e,"setState")},e}();e.exports=s},function(e,t,n){"use strict";function a(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1,this.updateQueue=new d(this)}var i=n(5),r=n(14),o=n(30),s=n(8),d=n(245),l=[];var c={enqueue:function(){}};i(a.prototype,o,{getTransactionWrappers:function(){return l},getReactMountReady:function(){return c},getUpdateQueue:function(){return this.updateQueue},destructor:function(){},checkpoint:function(){},rollback:function(){}}),r.addPoolingTo(a),e.exports=a},function(e,t,n){"use strict";(function(t){function a(e,t,n){if(e&&"object"==typeof e){var a=e,i=a[n]===void 0;!1,i&&null!=t&&(a[n]=t)}}var i=n(36),r=n(63),o=n(3);"undefined"!=typeof t&&t.env&&!1,e.exports=function(e){if(null==e)return e;var t={};return r(e,a,t),t}}).call(this,n(69))},function(e){"use strict";var t="function"==typeof Symbol&&Symbol.iterator;e.exports=function(e){var n=e&&(t&&e[t]||e["@@iterator"]);if("function"==typeof n)return n}},function(e){"use strict";var t="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;e.exports=t},function(e){"use strict";function t(){return n++}var n=1;e.exports=t},function(e,t,n){"use strict";function a(){}function i(){}function r(e){return!!(e.prototype&&e.prototype.isReactComponent)}function o(e){return!!(e.prototype&&e.prototype.isPureReactComponent)}var s=n(2),d=n(5),l=n(19),c=n(39),u=n(13),h=n(47),p=n(20),m=n(8),g=n(67),f=n(16);var w=n(66),y=n(1),v=n(38),b=n(37),x=n(3),_={ImpureClass:0,PureClass:1,StatelessFunctional:2};a.prototype.render=function(){var e=p.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return i(e,t),t};var E=1;e.exports={construct:function(e){this._currentElement=e,this._rootNodeID=0,this._compositeType=null,this._instance=null,this._hostParent=null,this._hostContainerInfo=null,this._updateBatchNumber=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedNodeType=null,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null,this._calledComponentWillUnmount=!1,!1},mountComponent:function(e,t,n,d){this;this._context=d,this._mountOrder=E++,this._hostParent=t,this._hostContainerInfo=n;var c=this._currentElement.props,u=this._processContext(d),h=this._currentElement.type,m=e.getUpdateQueue(),g=r(h),f=this._constructComponent(g,c,u,m),y;g||null!=f&&null!=f.render?o(h)?this._compositeType=_.PureClass:this._compositeType=_.ImpureClass:(y=f,i(h,y),null===f||!1===f||l.isValidElement(f)||!1?void 0:s("105",h.displayName||h.name||"Component"),f=new a(h),this._compositeType=_.StatelessFunctional);f.props=c,f.context=u,f.refs=w,f.updater=m,this._instance=f,p.set(f,this),!1;var v=f.state;void 0===v&&(f.state=v=null),("object"!=typeof v||Array.isArray(v))&&1?s("106",this.getName()||"ReactCompositeComponent"):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var b;return b=f.unstable_handleError?this.performInitialMountWithErrorHandling(y,t,n,e,d):this.performInitialMount(y,t,n,e,d),f.componentDidMount&&e.getReactMountReady().enqueue(f.componentDidMount,f),b},_constructComponent:function(e,t,n,a){return this._constructComponentWithoutOwner(e,t,n,a)},_constructComponentWithoutOwner:function(e,t,n,a){var i=this._currentElement.type;return e?new i(t,n,a):i(t,n,a)},performInitialMountWithErrorHandling:function(t,n,a,i,r){var o=i.checkpoint(),s;try{s=this.performInitialMount(t,n,a,i,r)}catch(d){i.rollback(o),this._instance.unstable_handleError(d),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),o=i.checkpoint(),this._renderedComponent.unmountComponent(!0),i.rollback(o),s=this.performInitialMount(t,n,a,i,r)}return s},performInitialMount:function(e,t,n,a,i){var r=this._instance;!1,r.componentWillMount&&(r.componentWillMount(),this._pendingStateQueue&&(r.state=this._processPendingState(r.props,r.context))),e===void 0&&(e=this._renderValidatedComponent());var o=g.getType(e);this._renderedNodeType=o;var s=this._instantiateReactComponent(e,o!==g.EMPTY);this._renderedComponent=s;var d=f.mountComponent(s,a,t,n,this._processChildContext(i),0);return d},getHostNode:function(){return f.getHostNode(this._renderedComponent)},unmountComponent:function(e){if(this._renderedComponent){var t=this._instance;if(t.componentWillUnmount&&!t._calledComponentWillUnmount)if(t._calledComponentWillUnmount=!0,e){var n=this.getName()+".componentWillUnmount()";h.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(f.unmountComponent(this._renderedComponent,e),this._renderedNodeType=null,this._renderedComponent=null,this._instance=null),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=0,this._topLevelWrapper=null,p.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return w;var a={};for(var i in n)a[i]=e[i];return a},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,a;if(n.getChildContext&&(a=n.getChildContext()),a){for(var i in"object"!=typeof t.childContextTypes&&1?s("107",this.getName()||"ReactCompositeComponent"):void 0,!1,a)i in t.childContextTypes||!1?void 0:s("108",this.getName()||"ReactCompositeComponent",i);return d({},e,a)}return e},_checkContextTypes:function(){},receiveComponent:function(e,t,n){var a=this._currentElement,i=this._context;this._pendingElement=null,this.updateComponent(t,a,e,i,n)},performUpdateIfNecessary:function(e){null==this._pendingElement?null!==this._pendingStateQueue||this._pendingForceUpdate?this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context):this._updateBatchNumber=null:f.receiveComponent(this,this._pendingElement,e,this._context)},updateComponent:function(e,t,n,a,i){var r=this._instance;null==r&&1?s("136",this.getName()||"ReactCompositeComponent"):void 0;var o=!1,d;this._context===i?d=r.context:(d=this._processContext(i),o=!0);var l=t.props,c=n.props;t!==n&&(o=!0),o&&r.componentWillReceiveProps&&r.componentWillReceiveProps(c,d);var u=this._processPendingState(c,d),h=!0;this._pendingForceUpdate||(r.shouldComponentUpdate?h=r.shouldComponentUpdate(c,u,d):this._compositeType===_.PureClass&&(h=!v(l,c)||!v(r.state,u))),!1,this._updateBatchNumber=null,h?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,c,u,d,e,i)):(this._currentElement=n,this._context=i,r.props=c,r.state=u,r.context=d)},_processPendingState:function(e,t){var n=this._instance,a=this._pendingStateQueue,r=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!a)return n.state;if(r&&1===a.length)return a[0];for(var o=d({},r?a[0]:n.state),s=r?1:0,l;s=d.length||!1?void 0:r("93"),d=d[0]),o=""+d),null==o&&(o=""),a=o}e._wrapperState={initialValue:""+a,listeners:null,onChange:i.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=d.getNodeFromInstance(e),a=s.getValue(t);if(null!=a){var i=""+a;i!==n.value&&(n.value=i),null==t.defaultValue&&(n.defaultValue=i)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e){var t=d.getNodeFromInstance(e),n=t.textContent;n===e._wrapperState.initialValue&&(t.value=n)}};e.exports=h},function(e,t,n){"use strict";function a(e){var t="";return r.Children.forEach(e,function(e){null==e||("string"==typeof e||"number"==typeof e?t+=e:!l&&(l=!0,!1,void 0))}),t}var i=n(5),r=n(19),o=n(4),s=n(70),d=n(3),l=!1;e.exports={mountWrapper:function(e,t,n){var r=null;if(null!=n){var o=n;"optgroup"===o._tag&&(o=o._hostParent),null!=o&&"select"===o._tag&&(r=s.getSelectValueContext(o))}var d=null;if(null!=r){var l;if(l=null==t.value?a(t.children):t.value+"",d=!1,Array.isArray(r)){for(var c=0;c>",d=d||i,c!==r)if(t){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}else;return null==a[i]?n?null===a[i]?new l("The "+s+" `"+d+"` is marked as required "+("in `"+o+"`, but its value is `null`.")):new l("The "+s+" `"+d+"` is marked as required in "+("`"+o+"`, but its value is `undefined`.")):null:e(a,i,o,s,d)}var a=n.bind(null,!1);return a.isRequired=n.bind(null,!0),a}function u(e){return c(function(t,n,a,i,r){var o=t[n],s=m(o);if(s!==e){var d=g(o);return new l("Invalid "+i+" `"+r+"` of type "+("`"+d+"` supplied to `"+a+"`, expected ")+("`"+e+"`."))}return null})}function h(t){switch(typeof t){case"number":case"string":case"undefined":return!0;case"boolean":return!t;case"object":if(Array.isArray(t))return t.every(h);if(null===t||e(t))return!0;var a=n(t);if(a){var i=a.call(t),r;if(a!==t.entries){for(;!(r=i.next()).done;)if(!h(r.value))return!1;}else for(;!(r=i.next()).done;){var o=r.value;if(o&&!h(o[1]))return!1}}else return!1;return!0;default:return!1;}}function p(e,t){return"symbol"===e||"Symbol"===t["@@toStringTag"]||!!("function"==typeof Symbol&&t instanceof Symbol)}function m(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":p(t,e)?"symbol":t}function g(e){if("undefined"==typeof e||null===e)return""+e;var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function f(e){var t=g(e);return"array"===t||"object"===t?"an "+t:"boolean"===t||"date"===t||"regexp"===t?"a "+t:t}function w(e){return e.constructor&&e.constructor.name?e.constructor.name:"<>"}var y="function"==typeof Symbol&&Symbol.iterator,v={array:u("array"),bool:u("boolean"),func:u("function"),number:u("number"),object:u("object"),string:u("string"),symbol:u("symbol"),any:function(){return c(a)}(),arrayOf:function(e){return c(function(t,n,a,o,s){if("function"!=typeof e)return new l("Property `"+s+"` of component `"+a+"` has invalid PropType notation inside arrayOf.");var d=t[n];if(!Array.isArray(d)){var c=m(d);return new l("Invalid "+o+" `"+s+"` of type "+("`"+c+"` supplied to `"+a+"`, expected an array."))}for(var u=0,h;u>",s=w(t[n]);return new l("Invalid "+i+" `"+r+"` of type "+("`"+s+"` supplied to `"+a+"`, expected ")+("instance of `"+o+"`."))}return null})},node:function(){return c(function(e,t,n,a,i){return h(e[t])?null:new l("Invalid "+a+" `"+i+"` supplied to "+("`"+n+"`, expected a ReactNode."))})}(),objectOf:function(e){return c(function(t,n,a,i,o){if("function"!=typeof e)return new l("Property `"+o+"` of component `"+a+"` has invalid PropType notation inside objectOf.");var s=t[n],d=m(s);if("object"!==d)return new l("Invalid "+i+" `"+o+"` of type "+("`"+d+"` supplied to `"+a+"`, expected an object."));for(var c in s)if(s.hasOwnProperty(c)){var u=e(s,c,a,i,o+"."+c,r);if(u instanceof Error)return u}return null})},oneOf:function(e){return Array.isArray(e)?c(function(t,n,a,r,o){for(var s=t[n],c=0;c",g=f.removeChild(f.firstChild)}else g=r.is?m.createElement(this._currentElement.type,r.is):m.createElement(this._currentElement.type);N.precacheNode(this,g),this._flags|=T.hasCachedChildNodes,this._hostParent||E.setAttributeForRoot(g),this._updateDOMProperties(null,r,e);var v=b(g);this._createInitialChildren(e,r,a,v),p=v}else{var _=this._createOpenTagMarkupAndPutListeners(e,r),C=this._createContentMarkup(e,r,a);p=!C&&$[this._tag]?_+"/>":_+">"+C+""}switch(this._tag){case"input":e.getReactMountReady().enqueue(s,this),r.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(d,this),r.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"select":r.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"button":r.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(l,this);}return p},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var a in t)if(t.hasOwnProperty(a)){var i=t[a];if(null!=i)if(H.hasOwnProperty(a))i&&r(this,a,i,e);else{a===Q&&(i&&(!1,i=this._previousStyleCopy=w({},t.style)),i=v.createMarkupForStyles(i,this));var o=null;null!=this._tag&&m(this._tag,t)?!Y.hasOwnProperty(a)&&(o=E.createMarkupForCustomAttribute(a,i)):o=E.createMarkupForProperty(a,i),o&&(n+=" "+o)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+E.createMarkupForRoot()),n+=" "+E.createMarkupForID(this._domID),n)},_createContentMarkup:function(e,t,n){var a="",i=t.dangerouslySetInnerHTML;if(null!=i)null!=i.__html&&(a=i.__html);else{var r=K[typeof t.children]?t.children:null,o=null==r?t.children:null;if(null!=r)a=O(r),!1;else if(null!=o){var s=this.mountChildren(o,e,n);a=s.join("")}}return ee[this._tag]&&"\n"===a.charAt(0)?"\n"+a:a},_createInitialChildren:function(e,t,n,a){var r=t.dangerouslySetInnerHTML;if(null!=r)null!=r.__html&&b.queueHTML(a,r.__html);else{var o=K[typeof t.children]?t.children:null,s=null==o?t.children:null;if(null!=o)""!==o&&(!1,b.queueText(a,o));else if(null!=s)for(var d=this.mountChildren(s,e,n),l=0;l",""],d=[1,"","
"],l=[3,"","
"],c=[1,"",""],u={"*":[1,"?
","
"],area:[1,"",""],col:[2,"","
"],legend:[1,"
","
"],param:[1,"",""],tr:[2,"","
"],optgroup:s,option:s,caption:d,colgroup:d,tbody:d,tfoot:d,thead:d,td:l,th:l};["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"].forEach(function(e){u[e]=c,o[e]=!0}),e.exports=function(e){return!r&&1?i(!1):void 0,u.hasOwnProperty(e)||(e="*"),o.hasOwnProperty(e)||(r.innerHTML="*"===e?"":"<"+e+">",o[e]=!r.firstChild),o[e]?u[e]:null}},function(e,t,n){"use strict";function a(e){var t=e.length;if((Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e)&&1?r(!1):void 0,"number"!=typeof t&&1?r(!1):void 0,0===t||t-1 in e||!1?void 0:r(!1),"function"==typeof e.callee&&1?r(!1):void 0,e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(t){}for(var n=Array(t),a=0;a=parseInt(e.version(),10)}(),_=m.canUseDOM&&(!v||b&&8=b),E={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},C=!1,k=null;e.exports={eventTypes:E,extractEvents:function(e,t,n,a){return[l(e,t,n,a),h(e,t,n,a)]}}},function(e){"use strict";e.exports={Properties:{"aria-current":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},DOMAttributeNames:{},DOMPropertyNames:{}}},function(e,t,n){"use strict";function a(){E||(E=!0,y.EventEmitter.injectReactEventListener(w),y.EventPluginHub.injectEventPluginOrder(s),y.EventPluginUtils.injectComponentTree(h),y.EventPluginUtils.injectTreeTraversal(m),y.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:_,EnterLeaveEventPlugin:d,ChangeEventPlugin:o,SelectEventPlugin:x,BeforeInputEventPlugin:r}),y.HostComponent.injectGenericComponentClass(u),y.HostComponent.injectTextComponentClass(g),y.DOMProperty.injectDOMPropertyConfig(i),y.DOMProperty.injectDOMPropertyConfig(l),y.DOMProperty.injectDOMPropertyConfig(b),y.EmptyComponent.injectEmptyComponentFactory(function(e){return new p(e)}),y.Updates.injectReconcileTransaction(v),y.Updates.injectBatchingStrategy(f),y.Component.injectEnvironment(c))}var i=n(290),r=n(289),o=n(285),s=n(282),d=n(281),l=n(280),c=n(279),u=n(273),h=n(4),p=n(244),m=n(243),g=n(242),f=n(241),w=n(240),y=n(238),v=n(237),b=n(231),x=n(230),_=n(229),E=!1;e.exports={inject:a}},function(e,t,n){"use strict";var a=n(4),i=n(291),r=n(58),o=n(16),s=n(9),d=n(215),l=n(214),c=n(57),u=n(213),h=n(3);i.inject();var p={findDOMNode:l,render:r.render,unmountComponentAtNode:r.unmountComponentAtNode,version:d,unstable_batchedUpdates:s.batchedUpdates,unstable_renderSubtreeIntoContainer:u};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:a.getClosestInstanceFromNode,getNodeFromInstance:function(e){return e._renderedComponent&&(e=c(e)),e?a.getNodeFromInstance(e):null}},Mount:r,Reconciler:o});e.exports=p},function(e,t,n){"use strict";e.exports=n(292)},function(e,t,n){"use strict";var a=n(25),i=n(18),r=n(24);e.exports=function(e){return i.isValidElement(e)||!1?void 0:a("143"),e}},function(e){"use strict";var t=function(){};!1,e.exports=function(n,i,r,a,o,s,d,e){if(t(i),!n){var l;if(void 0===i)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,a,o,s,d,e],u=0;l=new Error(i.replace(/%s/g,function(){return c[u++]})),l.name="Invariant Violation"}throw l.framesToPop=1,l}}},function(e){"use strict";!1,e.exports={}},function(e){"use strict";function t(e){if(null===e||e===void 0)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;10>n;n++)t["_"+a(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"].forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}()?Object.assign:function(e){for(var a=t(e),o=1,d,l;o>",d=d||i,c!==r)if(t){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}else;return null==a[i]?n?null===a[i]?new l("The "+s+" `"+d+"` is marked as required "+("in `"+o+"`, but its value is `null`.")):new l("The "+s+" `"+d+"` is marked as required in "+("`"+o+"`, but its value is `undefined`.")):null:e(a,i,o,s,d)}var a=n.bind(null,!1);return a.isRequired=n.bind(null,!0),a}function u(e){return c(function(t,n,a,i,r){var o=t[n],s=m(o);if(s!==e){var d=g(o);return new l("Invalid "+i+" `"+r+"` of type "+("`"+d+"` supplied to `"+a+"`, expected ")+("`"+e+"`."))}return null})}function h(t){switch(typeof t){case"number":case"string":case"undefined":return!0;case"boolean":return!t;case"object":if(Array.isArray(t))return t.every(h);if(null===t||e(t))return!0;var a=n(t);if(a){var i=a.call(t),r;if(a!==t.entries){for(;!(r=i.next()).done;)if(!h(r.value))return!1;}else for(;!(r=i.next()).done;){var o=r.value;if(o&&!h(o[1]))return!1}}else return!1;return!0;default:return!1;}}function p(e,t){return"symbol"===e||"Symbol"===t["@@toStringTag"]||!!("function"==typeof Symbol&&t instanceof Symbol)}function m(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":p(t,e)?"symbol":t}function g(e){if("undefined"==typeof e||null===e)return""+e;var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function f(e){var t=g(e);return"array"===t||"object"===t?"an "+t:"boolean"===t||"date"===t||"regexp"===t?"a "+t:t}function w(e){return e.constructor&&e.constructor.name?e.constructor.name:"<>"}var y="function"==typeof Symbol&&Symbol.iterator,v={array:u("array"),bool:u("boolean"),func:u("function"),number:u("number"),object:u("object"),string:u("string"),symbol:u("symbol"),any:function(){return c(a)}(),arrayOf:function(e){return c(function(t,n,a,o,s){if("function"!=typeof e)return new l("Property `"+s+"` of component `"+a+"` has invalid PropType notation inside arrayOf.");var d=t[n];if(!Array.isArray(d)){var c=m(d);return new l("Invalid "+o+" `"+s+"` of type "+("`"+c+"` supplied to `"+a+"`, expected an array."))}for(var u=0,h;u>",s=w(t[n]);return new l("Invalid "+i+" `"+r+"` of type "+("`"+s+"` supplied to `"+a+"`, expected ")+("instance of `"+o+"`."))}return null})},node:function(){return c(function(e,t,n,a,i){return h(e[t])?null:new l("Invalid "+a+" `"+i+"` supplied to "+("`"+n+"`, expected a ReactNode."))})}(),objectOf:function(e){return c(function(t,n,a,i,o){if("function"!=typeof e)return new l("Property `"+o+"` of component `"+a+"` has invalid PropType notation inside objectOf.");var s=t[n],d=m(s);if("object"!==d)return new l("Invalid "+i+" `"+o+"` of type "+("`"+d+"` supplied to `"+a+"`, expected an object."));for(var c in s)if(s.hasOwnProperty(c)){var u=e(s,c,a,i,o+"."+c,r);if(u instanceof Error)return u}return null})},oneOf:function(e){return Array.isArray(e)?c(function(t,n,a,r,o){for(var s=t[n],c=0;c