openstamanager/assets/src/js/wacom/sigCaptDialog/libs/will/digital-ink/workers/SplitPointsProvider.mjs

2 lines
151 KiB
JavaScript
Executable File

import"js-ext";import{vec2 as e,vec3 as t,vec4 as i,mat4 as s,quat2 as r,mat2d as n}from"gl-matrix";import*as a from"poly2tri";import*as o from"clipper-lib";import l from"long";import*as h from"js-md5";import u from"rbush";"function"==typeof Worker&&(Worker.prototype.on=function(e,t){this[`on${e}`]=i=>{let s="message"==e?i.data:i;t(s)}}),"function"==typeof DedicatedWorkerGlobalScope&&(DedicatedWorkerGlobalScope.prototype.on=function(e,t){this[`on${e}`]=i=>{let s="message"==e?i.data:i;t(s)}});class p{constructor(e,t){e>0&&0==t?(this.segmentIndex=e-1,this.t=1):(this.segmentIndex=e,this.t=t),Object.defineProperty(this,"index",{get:()=>(console.warn("SplineParameter index => segmentIndex"),this.segmentIndex)})}equals(e){return this.segmentIndex==e.segmentIndex&&this.t==e.t}toString(){return`spline-parameter(${this.segmentIndex}, ${this.t})`}toJSON(){return{segmentIndex:this.segmentIndex,t:this.t}}static fromJSON(e){return new p(e.segmentIndex,e.t)}static calcMiddleOfSegment(e,t){let i=.5*(e.t+t.t+(t.segmentIndex-e.segmentIndex)),s=Math.trunc(i),r=i-s;return new p(e.segmentIndex+s,r)}static areDistantEnough(e,t,i=.01){return t.t+(t.segmentIndex-e.segmentIndex)-e.t>i}}class c{constructor(e,t,i){this.splineParameter=e,this.segmentIndex=t,this.on=i}toString(){return`SplineSplitPoint: ${this.splineParameter.segmentIndex} T:${this.splineParameter.t} -> ${this.on?"ON":"OFF"}, split by ${this.segmentIndex}`}toJSON(){return{splineParameter:this.splineParameter.toJSON(),segmentIndex:this.segmentIndex,on:this.on}}static fromJSON(e){return new c(p.fromJSON(e.splineParameter),e.segmentIndex,e.on)}static compare(e,t){return e.splineParameter.segmentIndex<t.splineParameter.segmentIndex?-1:e.splineParameter.segmentIndex>t.splineParameter.segmentIndex?1:e.splineParameter.t<t.splineParameter.t?-1:e.splineParameter.t>t.splineParameter.t?1:0}}class d{constructor(s,r,n,a){if(isNaN(s))throw new Error(`Invalid x found: ${s}`);if(isNaN(r))throw new Error(`Invalid y found: ${r}`);let o=[s,r];isFinite(n)&&(o.push(n),isFinite(a)&&o.push(a)),this.value=o.toFloat32Array(),Object.defineProperty(this,"x",{get:()=>this.value[0],set:e=>{this.value[0]=e},enumerable:!0}),Object.defineProperty(this,"y",{get:()=>this.value[1],set:e=>{this.value[1]=e},enumerable:!0}),2==o.length?this.vec=e:3==o.length?(this.vec=t,Object.defineProperty(this,"z",{get:()=>this.value[2],set:e=>{this.value[2]=e},enumerable:!0})):(this.vec=i,Object.defineProperty(this,"w",{get:()=>this.value[3],set:e=>{this.value[3]=e},enumerable:!0}))}add(e){e instanceof d||(e=d.fromPoint(e));let t=this.vec.create();return this.vec.add(t,this.value,e.value),d.fromPoint(t)}addSelf(e){return e instanceof d||(e=d.fromPoint(e)),this.vec.add(this.value,this.value,e.value),this}subtract(e){e instanceof d||(e=d.fromPoint(e));let t=this.vec.create();return this.vec.subtract(t,this.value,e.value),d.fromPoint(t)}subtractSelf(e){return e instanceof d||(e=d.fromPoint(e)),this.vec.subtract(this.value,this.value,e.value),this}multiply(e){e instanceof d||(e=d.fromPoint(e));let t=this.vec.create();return this.vec.multiply(t,this.value,e.value),d.fromPoint(t)}multiplySelf(e){return e instanceof d||(e=d.fromPoint(e)),this.vec.multiply(this.value,this.value,e.value),this}divide(e){e instanceof d||(e=d.fromPoint(e));let t=this.vec.create();return this.vec.divide(t,this.value,e.value),d.fromPoint(t)}divideSelf(e){return e instanceof d||(e=d.fromPoint(e)),this.vec.divide(this.value,this.value,e.value),this}scale(e){let t=this.vec.create();return this.vec.scale(t,this.value,e),d.fromPoint(t)}scaleSelf(e){return this.vec.scale(this.value,this.value,e),this}abs(){return new d(Math.abs(this.x),Math.abs(this.y),isFinite(this.z)?Math.abs(this.z):void 0,isFinite(this.w)?Math.abs(this.w):void 0)}absSelf(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),isFinite(this.z)&&(this.z=Math.abs(this.z)),isFinite(this.w)&&(this.w=Math.abs(this.w)),this}transform(e){if(!e)return this;let t=this.vec.create();return this.vec.transformMat4(t,this.value,e.toFloat32Array()),d.fromPoint(t)}transformSelf(e){return this.vec.transformMat4(this.value,this.value,e.toFloat32Array()),this}toFloat32Array(){return this.value}toJSON(){let e={x:this.x,y:this.y};return isFinite(this.z)&&(e.z=this.z,isFinite(this.w)&&(e.w=this.w)),e}toString(){return`point(${this.value.join(", ")})`}clone(){return d.fromPoint(this)}static fromPoint(e){return Array.isArray(e)||ArrayBuffer.isTypedArray(e)?new d(e[0],e[1],e[2],e[3]):new d(e.x,e.y,e.z,e.w)}}const f={m11:0,m12:1,m13:2,m14:3,m21:4,m22:5,m23:6,m24:7,m31:8,m32:9,m33:10,m34:11,m41:12,m42:13,m43:14,m44:15},m=f.m11,g=f.m12,y=f.m21,P=f.m22,b=f.m41,E=f.m42;class S{constructor(e=s.create(),t=S.MultiplicationType.PRE){Object.defineProperty(this,"value",{value:e,enumerable:!0}),Object.defineProperty(this,"multiplicationType",{value:t,enumerable:!0});let i=function(e,t){let i=f[e];this.value[i]=t};Object.defineProperty(this,"a",{get:()=>this.value[m],set:i.bind(this,"m11"),enumerable:!0}),Object.defineProperty(this,"b",{get:()=>this.value[g],set:i.bind(this,"m12"),enumerable:!0}),Object.defineProperty(this,"c",{get:()=>this.value[y],set:i.bind(this,"m21"),enumerable:!0}),Object.defineProperty(this,"d",{get:()=>this.value[P],set:i.bind(this,"m22"),enumerable:!0}),Object.defineProperty(this,"e",{get:()=>this.value[b],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"f",{get:()=>this.value[E],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"tx",{get:()=>this.value[b],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"ty",{get:()=>this.value[E],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"m11",{get:()=>this.value[0],set:i.bind(this,"m11"),enumerable:!0}),Object.defineProperty(this,"m12",{get:()=>this.value[1],set:i.bind(this,"m12"),enumerable:!0}),Object.defineProperty(this,"m13",{get:()=>this.value[2],set:i.bind(this,"m13"),enumerable:!0}),Object.defineProperty(this,"m14",{get:()=>this.value[3],set:i.bind(this,"m14"),enumerable:!0}),Object.defineProperty(this,"m21",{get:()=>this.value[4],set:i.bind(this,"m21"),enumerable:!0}),Object.defineProperty(this,"m22",{get:()=>this.value[5],set:i.bind(this,"m22"),enumerable:!0}),Object.defineProperty(this,"m23",{get:()=>this.value[6],set:i.bind(this,"m23"),enumerable:!0}),Object.defineProperty(this,"m24",{get:()=>this.value[7],set:i.bind(this,"m24"),enumerable:!0}),Object.defineProperty(this,"m31",{get:()=>this.value[8],set:i.bind(this,"m31"),enumerable:!0}),Object.defineProperty(this,"m32",{get:()=>this.value[9],set:i.bind(this,"m32"),enumerable:!0}),Object.defineProperty(this,"m33",{get:()=>this.value[10],set:i.bind(this,"m33"),enumerable:!0}),Object.defineProperty(this,"m34",{get:()=>this.value[11],set:i.bind(this,"m34"),enumerable:!0}),Object.defineProperty(this,"m41",{get:()=>this.value[12],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"m42",{get:()=>this.value[13],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"m43",{get:()=>this.value[14],set:i.bind(this,"m43"),enumerable:!0}),Object.defineProperty(this,"m44",{get:()=>this.value[15],set:i.bind(this,"m44"),enumerable:!0}),Object.defineProperty(this,"isIdentity",{get:()=>1==this.a&&0==this.b&&0==this.c&&1==this.d&&0==this.tx&&0==this.ty,enumerable:!0}),Object.defineProperty(this,"is2D",{get:()=>!(0!=this.m31||0!=this.m32||0!=this.m13||0!=this.m23||1!=this.m33||0!=this.m43||0!=this.m14||0!=this.m24||0!=this.m34||1!=this.m44),enumerable:!0}),Object.defineProperty(this,"translateX",{get:()=>this.tx}),Object.defineProperty(this,"translateY",{get:()=>this.ty}),Object.defineProperty(this,"skewX",{get:()=>Math.tan(this.c)}),Object.defineProperty(this,"skewY",{get:()=>Math.tan(this.b)}),Object.defineProperty(this,"scaleX",{get:()=>Math.sqrt(this.a*this.a+this.c*this.c)}),Object.defineProperty(this,"scaleY",{get:()=>Math.sqrt(this.d*this.d+this.b*this.b)}),Object.defineProperty(this,"rotation",{get:()=>Math.atan2(this.b,this.a)})}clone(){return new S(this.value.clone(),this.multiplicationType)}translate(e){return this.multiply(S.fromTranslate(e))}translateSelf(e){this.multiplySelf(S.fromTranslate(e))}rotate(e,t){return this.multiply(S.fromRotate(e,t))}rotateSelf(e,t){this.multiplySelf(S.fromRotate(e,t))}scale(e,t){return this.multiply(S.fromScale(e,t))}scaleSelf(e,t){this.multiplySelf(S.fromScale(e,t))}multiply(e){return this.multiplicationType==S.MultiplicationType.PRE?this.preMultiply(e):this.postMultiply(e)}preMultiply(e){let t=s.create();return s.multiply(t,e.toFloat32Array(),this.value),new S(t,this.multiplicationType)}postMultiply(e){let t=s.create();return s.multiply(t,this.value,e.toFloat32Array()),new S(t,this.multiplicationType)}multiplySelf(e){this.multiplicationType==S.MultiplicationType.PRE?this.preMultiplySelf(e):this.postMultiplySelf(e)}preMultiplySelf(e){s.multiply(this.value,e.toFloat32Array(),this.value)}postMultiplySelf(e){s.multiply(this.value,this.value,e.toFloat32Array())}invert(){let e=s.create();return s.invert(e,this.value),new S(e,this.multiplicationType)}invertSelf(){s.invert(this.value,this.value)}decompose(){return{translate:{x:this.tx,y:this.ty},rotate:{angle:Math.atan2(this.b,this.a)},skew:{angleX:Math.tan(this.c),angleY:Math.tan(this.b)},scale:{x:Math.sqrt(this.a*this.a+this.c*this.c),y:Math.sqrt(this.d*this.d+this.b*this.b)},matrix:this.toJSON()}}transformPoint(e){return d.fromPoint(e).transform(this)}toFloat32Array(){return this.value}toJSON(){return{a:this.a,b:this.b,c:this.c,d:this.d,tx:this.tx,ty:this.ty}}toString(e){if(e){let e=e=>((e<0?"":" ")+e.toPrecision(6)).substring(0,8);return" Matrix 4x4\n"+"-".repeat(39)+`\n${e(this.m11)}, ${e(this.m21)}, ${e(this.m31)}, ${e(this.m41)}`+`\n${e(this.m12)}, ${e(this.m22)}, ${e(this.m32)}, ${e(this.m42)}`+`\n${e(this.m13)}, ${e(this.m23)}, ${e(this.m33)}, ${e(this.m43)}`+`\n${e(this.m14)}, ${e(this.m24)}, ${e(this.m34)}, ${e(this.m44)}`}return this.is2D?`matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.tx}, ${this.ty})`:`matrix3d(${this.m11}, ${this.m12}, ${this.m13}, ${this.m14}, ${this.m21}, ${this.m22}, ${this.m23}, ${this.m24}, ${this.m31}, ${this.m32}, ${this.m33}, ${this.m34}, ${this.m41}, ${this.m42}, ${this.m43}, ${this.m44})`}static fromString(e,t){let i=s.create();if("none"!=e){let t=e.substring(0,e.indexOf("("));e=e.substring(e.indexOf("(")+1,e.indexOf(")")).split(/,\s*/g),"matrix3d"==t?(i[0]=parseFloat(e[0]),i[1]=parseFloat(e[1]),i[2]=parseFloat(e[2]),i[3]=parseFloat(e[3]),i[4]=parseFloat(e[4]),i[5]=parseFloat(e[5]),i[6]=parseFloat(e[6]),i[7]=parseFloat(e[7]),i[8]=parseFloat(e[8]),i[9]=parseFloat(e[9]),i[10]=parseFloat(e[10]),i[11]=parseFloat(e[11]),i[12]=parseFloat(e[12]),i[13]=parseFloat(e[13]),i[14]=parseFloat(e[14]),i[15]=parseFloat(e[15])):(i[m]=parseFloat(e[0]),i[g]=parseFloat(e[1]),i[y]=parseFloat(e[2]),i[P]=parseFloat(e[3]),i[b]=parseFloat(e[4]),i[E]=parseFloat(e[5]))}return new S(i,t)}static fromMatrix(e,t){if(!e)throw new Error("data not found, Matrix instance creation failed");if("function"==typeof e)throw new Error("data type function is not allowed");if(e instanceof S)return e;if(Array.isArray(e)&&(e=new Float32Array(e)),e instanceof Float32Array)return new S(e,t);if("string"==typeof e)return S.fromString(e,t);let i=s.create(),r=Object.assign({},e);return isFinite(e.a)&&(r.m11=e.a),isFinite(e.b)&&(r.m12=e.b),isFinite(e.c)&&(r.m21=e.c),isFinite(e.d)&&(r.m22=e.d),isFinite(e.tx)?r.m41=e.tx:isFinite(e.e)?r.m41=e.e:isFinite(e.dx)&&(r.m41=e.dx),isFinite(e.ty)?r.m42=e.ty:isFinite(e.f)?r.m42=e.f:isFinite(e.dy)&&(r.m42=e.dy),isFinite(r.m11)&&(i[0]=r.m11),isFinite(r.m12)&&(i[1]=r.m12),isFinite(r.m13)&&(i[2]=r.m13),isFinite(r.m14)&&(i[3]=r.m14),isFinite(r.m21)&&(i[4]=r.m21),isFinite(r.m22)&&(i[5]=r.m22),isFinite(r.m23)&&(i[6]=r.m23),isFinite(r.m24)&&(i[7]=r.m24),isFinite(r.m31)&&(i[8]=r.m31),isFinite(r.m32)&&(i[9]=r.m32),isFinite(r.m33)&&(i[10]=r.m33),isFinite(r.m34)&&(i[11]=r.m34),isFinite(r.m41)&&(i[12]=r.m41),isFinite(r.m42)&&(i[13]=r.m42),isFinite(r.m43)&&(i[14]=r.m43),isFinite(r.m44)&&(i[15]=r.m44),new S(i,t||e.multiplicationType)}static fromTranslate(e){let t=isFinite(e)?{tx:e,ty:e}:{tx:e.x,ty:e.y};return S.fromMatrix(t)}static fromRotate(e,t){let i=Math.sin(e),s=Math.cos(e),r={a:s,b:i,c:-i,d:s};return t&&(r.tx=t.x-t.x*s+t.y*i,r.ty=t.y-t.x*i-t.y*s),S.fromMatrix(r)}static fromScale(e,t){isFinite(e)&&(e={x:e,y:e});let i={a:e.x,d:e.y};return t&&(i.tx=t.x-t.x*e.x,i.ty=t.y-t.y*e.y),S.fromMatrix(i)}static fromPoints(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Expected input type Array requirement not satisfied");if(3!=e.length||3!=t.length)throw new Error("Expected input size 3 requirement not satisfied");let i=S.fromMatrix({m11:e[0].x,m21:e[1].x,m31:e[2].x,m12:e[0].y,m22:e[1].y,m32:e[2].y,m13:1,m23:1,m33:1}),s=S.fromMatrix({m11:t[0].x,m21:t[1].x,m31:t[2].x,m12:t[0].y,m22:t[1].y,m32:t[2].y,m13:1,m23:1,m33:1}),r=i.invert().preMultiply(s);return S.fromMatrix({a:r.m11,b:r.m12,c:r.m21,d:r.m22,tx:r.m31,ty:r.m32})}static multiply(e,t){let i=s.create();return s.multiply(i,e.value,t.value),new S(i)}}S.MultiplicationType=Object.freeze({PRE:"PRE",POST:"POST"});class w extends d{static defaults={size:1,rotation:0,scaleX:1,scaleY:1,scaleZ:1,offsetX:0,offsetY:0,offsetZ:0};constructor(e,t,i,s={}){super(e,t,i),this.red=s.red,this.green=s.green,this.blue=s.blue,this.alpha=s.alpha,this.size=s.size||w.defaults.size,this.rotation=s.rotation||w.defaults.rotation,this.scaleX=s.scaleX||w.defaults.scaleX,this.scaleY=s.scaleY||w.defaults.scaleY,this.scaleZ=isFinite(i)?s.scaleZ||w.defaults.scaleZ:void 0,this.offsetX=s.offsetX||w.defaults.offsetX,this.offsetY=s.offsetY||w.defaults.offsetY,this.offsetZ=isFinite(i)?s.offsetZ||w.defaults.offsetZ:void 0,this.dX,this.dY}static createInstance(e,t,i,s=0){let r=new w(0,0,e.includes(w.Property.Z)?0:void 0);return i&&r.fill(s,i,e,t),r}fill(e,t,i,s={}){let r={},n=e*i.length;i.forEach(((e,i)=>w.setProperty(r,e,t[n+i]))),this.x=r.x,this.y=r.y,this.z=r.z,this.red=isFinite(r.red)?r.red:s.red,this.green=isFinite(r.green)?r.green:s.green,this.blue=isFinite(r.blue)?r.blue:s.blue,this.alpha=isFinite(r.alpha)?r.alpha:s.alpha,this.size=r.size||s.size||w.defaults.size,this.rotation=r.rotation||s.rotation||w.defaults.rotation,this.scaleX=r.scaleX||s.scaleX||w.defaults.scaleX,this.scaleY=r.scaleY||s.scaleY||w.defaults.scaleY,this.scaleZ=isFinite(r.z)?r.scaleZ||s.scaleZ||w.defaults.scaleZ:void 0,this.offsetX=r.offsetX||s.offsetX||w.defaults.offsetX,this.offsetY=r.offsetY||s.offsetY||w.defaults.offsetY,this.offsetZ=isFinite(r.z)?r.offsetZ||s.offsetZ||w.defaults.offsetZ:void 0,this.dX=r.dX,this.dY=r.dY}getProperty(e){switch(e){case w.Property.X:return this.x;case w.Property.Y:return this.y;case w.Property.Z:return this.z;case w.Property.RED:return this.red;case w.Property.GREEN:return this.green;case w.Property.BLUE:return this.blue;case w.Property.ALPHA:return this.alpha;case w.Property.SIZE:return this.size;case w.Property.ROTATION:return this.rotation;case w.Property.SCALE_X:return this.scaleX;case w.Property.SCALE_Y:return this.scaleY;case w.Property.SCALE_Z:return this.scaleZ;case w.Property.OFFSET_X:return this.offsetX;case w.Property.OFFSET_Y:return this.offsetY;case w.Property.OFFSET_Z:return this.offsetZ;case w.Property.D_X:return this.dX;case w.Property.D_Y:return this.dY;default:throw console.warn(e),new Error("Invalid property found")}}setProperty(e,t){w.setProperty(this,e,t)}static setProperty(e,t,i){switch(t){case w.Property.X:e.x=i;break;case w.Property.Y:e.y=i;break;case w.Property.Z:e.z=i;break;case w.Property.RED:e.red=i;break;case w.Property.GREEN:e.green=i;break;case w.Property.BLUE:e.blue=i;break;case w.Property.ALPHA:e.alpha=i;break;case w.Property.SIZE:e.size=i;break;case w.Property.ROTATION:e.rotation=i;break;case w.Property.SCALE_X:e.scaleX=i;break;case w.Property.SCALE_Y:e.scaleY=i;break;case w.Property.SCALE_Z:e.scaleZ=i;break;case w.Property.OFFSET_X:e.offsetX=i;break;case w.Property.OFFSET_Y:e.offsetY=i;break;case w.Property.OFFSET_Z:e.offsetZ=i;break;case w.Property.D_X:e.dX=i;break;case w.Property.D_Y:e.dY=i;break;default:throw console.warn(t),new Error("Invalid property found")}}transform(e){if(!(e instanceof S))throw new Error(`matrix is instance of ${e.constructor.name} - it should be instance of Matrix. Use Matrix.fromMatrix method to convert.`);let t=e.scaleX,i=e.rotation;this.transformSelf(e),this.size*=t,this.rotation+=i}toArray(e){return e.map((e=>{let t=this.getProperty(e);if(null==t||isNaN(t))throw new Error(`Property ${e.name} has invalid value ${t}`);return t}))}toJSON(){let e={};return w.Property.values.forEach((t=>{let i=this.getProperty(t);null!=i&&isFinite(i)&&(e[t.name]=this.getProperty(t))})),e}}Object.defineEnum(w,"Property",["X","Y","Z","RED","GREEN","BLUE","ALPHA","SIZE","ROTATION","SCALE_X","SCALE_Y","SCALE_Z","OFFSET_X","OFFSET_Y","OFFSET_Z","D_X","D_Y"]);class I{constructor(e){this.key=e,this.height=1}leftRotate(){let e=this.right,t=e.left;return e.left=this,this.right=t,this.height=Math.max(I.height(this.left),I.height(this.right))+1,e.height=Math.max(I.height(e.left),I.height(e.right))+1,e}rightRotate(){let e=this.left,t=e.right;return e.right=this,this.left=t,this.height=Math.max(I.height(this.left),I.height(this.right))+1,e.height=Math.max(I.height(e.left),I.height(e.right))+1,e}getBalanceFactor(){return I.height(this.left)-I.height(this.right)}static height(e){return e?e.height:0}static minValue(e){if(!e)return;let t=e;for(;t.left;)t=t.left;return t.key}static maxValue(e){if(!e)return;let t=e;for(;t.right;)t=t.right;return t.key}}class O{constructor(){this.count=0,this.hasKey=!1,this.root}min(){return I.minValue(this.root)}max(){return I.maxValue(this.root)}add(e){return this.hasKey=!1,this.root=this.insertNode(this.root,e),this.hasKey||this.count++,!this.hasKey}insertNode(e,t){if(!e)return new I(t);if(t<e.key)e.left=this.insertNode(e.left,t);else{if(!(t>e.key))return this.hasKey=!0,e;e.right=this.insertNode(e.right,t)}if(!this.hasKey){e.height=1+Math.max(I.height(e.left),I.height(e.right));let i=e.getBalanceFactor();if(i>1){if(t<e.left.key)return e.rightRotate();if(t>e.left.key)return e.left=e.left.leftRotate(),e.rightRotate()}else if(i<-1){if(t>e.right.key)return e.leftRotate();if(t<e.right.key)return e.right=e.right.rightRotate(),e.leftRotate()}}return e}contains(e){return this.containsNode(this.root,e)}containsNode(e,t){return!!e&&(t<e.key?this.containsNode(e.left,t):!(t>e.key)||this.containsNode(e.right,t))}printTree(){if(!this.root)return;let e=[this.root],t=this.root.height;for(;e.length>0;){let i=e.shift();t!=i.height&&console.log("-"),console.log(`${i.key} with height: ${i.height}, balance: ${i.getBalanceFactor()}`),t=i.height;let s=i.left,r=i.right;s&&e.push(s),r&&e.push(r)}}toArray(){let e=[];return O.fillArray(e,this.root),e}static fillArray(e,t){t&&(this.fillArray(e,t.left),e.push(t.key),this.fillArray(e,t.right))}}class v{constructor(){this.tree=new O,Object.defineProperty(this,"length",{get:()=>this.tree.count,enumerable:!0})}clear(){this.tree=new O}add(e){return this.tree.add(e)}includes(e){return this.tree.contains(e)}min(){return this.tree.min()}max(){return this.tree.max()}toArray(){return this.tree.toArray()}}let x=a?a.default||globalThis.poly2tri:{};const{SweepContext:A,Point:R}=x;let T=o?o.default||globalThis.ClipperLib:{};const{Clipper:D,Paths:N,Path:F,ClipType:C,PolyType:M,PolyFillType:k}=T;class L{constructor(e,t,i){Object.defineProperties(this,{path:{value:e,enumerable:!0},pointIndexStart:{value:t,enumerable:!0},pointIndexEnd:{value:i,enumerable:!0}}),this.validate()}validate(){if(this.pointIndexStart<0)throw new Error(`Invalid fragment pointIndexStart ${this.pointIndexStart} found. The value must be non-negative.`);if(this.pointIndexEnd>this.path.length-1)throw new Error(`Invalid fragment pointIndexEnd ${this.pointIndexEnd} found. Last point in path index is ${this.path.length-1}.`)}toPath(){return this.path.slice(this)}toString(){return`fragment(${this.pointIndexStart} - ${this.pointIndexEnd})`}}class B{constructor(e,t,i,s=1){if(this.red=e,this.green=t,this.blue=i,this.alpha=s,s<0||s>1)throw new Error(`Invalid alpha ${s} found. The value must be in the interval [0, 1].`);Object.defineProperty(this,"hex",{get:()=>`#${this.red.toString(16).pad(2,"0")}${this.green.toString(16).pad(2,"0")}${this.blue.toString(16).pad(2,"0")}${Math.round(255*this.alpha).toString(16).pad(2,"0")}`,enumerable:!0})}premultiply(){return{red:this.red/255*this.alpha,green:this.green/255*this.alpha,blue:this.blue/255*this.alpha,alpha:this.alpha}}static postdivide(e,t,i,s){let r=parseInt(255*e/s),n=parseInt(255*t/s),a=parseInt(255*i/s);return new B(r,n,a,s)}equals(e){return e&&this.red==e.red&&this.green==e.green&&this.blue==e.blue&&this.alpha==e.alpha}toRGB(){return 1==this.alpha?this:new B(this.red,this.green,this.blue)}toRGBA(e){return new B(this.red,this.green,this.blue,e)}toHSLA(){let e=this.red/255,t=this.green/255,i=this.blue/255,s=Math.min(e,t,i),r=Math.max(e,t,i),n=0,a=0,o=(r+s)/2;if(r!=s){let l=r-s;switch(a=l/(1-Math.abs(2*o-1)),r){case e:n=(t-i)/l%6;break;case t:n=(i-e)/l+2;break;case i:n=(e-t)/l+4}}return n*=60,n<0&&(n+=360),{hue:parseFloat(n.toFixed(0)),saturation:parseFloat((100*a).toFixed(2)),lightness:parseFloat((100*o).toFixed(2)),alpha:this.alpha}}toArray(){return[this.red,this.green,this.blue,this.alpha]}toJSON(){return{red:this.red,green:this.green,blue:this.blue,alpha:this.alpha}}toString(){return 1==this.alpha?`rgb(${this.red}, ${this.green}, ${this.blue})`:`rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`}static isColor(e){return e&&isFinite(e.red)&&isFinite(e.green)&&isFinite(e.blue)}static fromColor(e){let t,i,s,r;if("string"==typeof e)if(e.startsWith("rgb"))e=e.substring(e.indexOf("(")+1,e.indexOf(")")).split(/,\s*/g),t=parseInt(e[0]),i=parseInt(e[1]),s=parseInt(e[2]),r=e[3]?parseInt(e[3]):1;else{if(!e.startsWith("#"))throw new Error(`Unknown input found: ${e}. Expected data starts with rgba, rgb or #.`);e=e.substring(1),t=parseInt(e.substring(0,2),16),i=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16),r=8==e.length?parseInt(e.substring(6,8),16)/255:1}else Array.isArray(e)?(t=e[0],i=e[1],s=e[2],r=e[3]):(t=e.red,i=e.green,s=e.blue,r=e.alpha);return new B(t,i,s,r)}static fromHSLA(e=0,t=0,i=0,s){e/=60,t/=100,i/=100;let r=(1-Math.abs(2*i-1))*t,n=r*(1-Math.abs(e%2-1)),a=0,o=0,l=0;e>=0&&e<1?(a=r,o=n):e>=1&&e<2?(a=n,o=r):e>=2&&e<3?(o=r,l=n):e>=3&&e<4?(o=n,l=r):e>=4&&e<5?(a=n,l=r):(a=r,l=n);let h=i-r/2;return a+=h,o+=h,l+=h,new B(Math.round(255*a),Math.round(255*o),Math.round(255*l),s)}static random(e=!1){return new B(Math.randomInt(0,255),Math.randomInt(0,255),Math.randomInt(0,255),e?Math.random():1)}}B.TRANSPERENT=new B(0,0,0,0),B.BLACK=new B(0,0,0,1),B.WHITE=new B(255,255,255,1),B.RED=new B(255,0,0,1),B.GREEN=new B(0,255,0,1),B.BLUE=new B(0,0,255,1);let _={longToByteArray(e){let t=[0,0,0,0,0,0,0,0];for(let i=0;i<t.length;i++){let s=255&e;t[i]=s,e=(e-s)/256}return t},byteArrayToLong(e){let t=0;for(let i=e.length-1;i>=0;i--)t=256*t+e[i];return t},crc32:function(){let e=new Uint32Array(256);for(let t=256;t--;){let i=t;for(let e=8;e--;)i=1&i?3988292384^i>>>1:i>>>1;e[t]=i}return function(t){let i=-1;for(let s=0,r=t.length;s<r;s++)i=i>>>8^e[255&i^t[s]];return(-1^i)>>>0}}(),encodeBitMask(e=[]){if(0==e.length)return 0;let t="",i=Math.max(...e);for(let s=1;s<=i;s++)t+=e.includes(s)?"1":"0";return parseInt(t.split("").reverse().join(""),2)},decodeBitMask(e){let t=[],i=e.toString(2).split("").reverse();for(let e=0;e<i.length;e++)1==i[e]&&t.push(e+1);return t},mapTo:(e,t,i)=>i.min+(_.clamp(e,t)-t.min)/(t.max-t.min)*(i.max-i.min),clamp:(e,t)=>Math.min(Math.max(e,t.min),t.max),debounce(e,t){let i=null;return function(){let s=this,r=arguments;clearTimeout(i),i=setTimeout((function(){e.apply(s,r)}),t)}},comparator(){let e=Array.prototype.slice.call(arguments),t=function(e,t,i){return t.replace("[",".").replace("]","").split(".").forEach((t=>e=e[t])),i?e.toLowerCase():e};return function(i,s){return e.map((e=>function(e,t,i){let s="asc"===i?1:-1;return e>t?1*s:e<t?-1*s:0}(t(i,e.sortBy,e.ignoreCase),t(s,e.sortBy,e.ignoreCase),e.sortOrder))).reduceRight((function(e,t){return t||e}))}},isValidURL(e){if("string"!=typeof e)return!1;try{return new URL(e),!0}catch(e){return!1}},getPropName(e,t){let i=e.split("_"),s=i.first.toLowerCase();t&&(s=s.substring(0,1).toUpperCase()+s.substring(1));for(let e=1;e<i.length;e++)s+=i[e].substring(0,1),s+=i[e].substring(1).toLowerCase();return s},getEnumValueName(e){let t="";for(let i=0;i<e.length;i++)i>0&&e[i]!=e[i].toLowerCase()&&(t+="_"),t+=e[i];return t.toUpperCase()}};class j{constructor(e,t,i={}){this.layout=e,this.pointProps=t,this.sheet={};let s={};Object.defineProperties(s,{size:{get:this.getComputed.bind(this,"size"),set:this.setStyle.bind(this,"size"),enumerable:!0},red:{get:this.getComputed.bind(this,"red"),set:this.setStyle.bind(this,"red"),enumerable:!0},green:{get:this.getComputed.bind(this,"green"),set:this.setStyle.bind(this,"green"),enumerable:!0},blue:{get:this.getComputed.bind(this,"blue"),set:this.setStyle.bind(this,"blue"),enumerable:!0},alpha:{get:this.getComputed.bind(this,"alpha"),set:this.setStyle.bind(this,"alpha"),enumerable:!0},rotation:{get:this.getComputed.bind(this,"rotation"),set:this.setStyle.bind(this,"rotation"),enumerable:!0},scaleX:{get:this.getComputed.bind(this,"scaleX"),set:this.setStyle.bind(this,"scaleX"),enumerable:!0},scaleY:{get:this.getComputed.bind(this,"scaleY"),set:this.setStyle.bind(this,"scaleY"),enumerable:!0},scaleZ:{get:this.getComputed.bind(this,"scaleZ"),set:this.setStyle.bind(this,"scaleZ"),enumerable:!0},offsetX:{get:this.getComputed.bind(this,"offsetX"),set:this.setStyle.bind(this,"offsetX"),enumerable:!0},offsetY:{get:this.getComputed.bind(this,"offsetY"),set:this.setStyle.bind(this,"offsetY"),enumerable:!0},offsetZ:{get:this.getComputed.bind(this,"offsetZ"),set:this.setStyle.bind(this,"offsetZ"),enumerable:!0},color:{get:this.getComputed.bind(this,"color"),set:this.setStyle.bind(this,"color"),enumerable:!0},blendMode:{get:this.getComputed.bind(this,"blendMode"),set:this.setStyle.bind(this,"blendMode"),enumerable:!0},visibility:{get:this.getComputed.bind(this,"visibility"),set:this.setStyle.bind(this,"visibility"),enumerable:!0},reset:{value:e=>{e&&(i=e),this.clear(),Object.keys(i).forEach((e=>this.setStyle(e,i[e])))}},clear:{value:this.clear.bind(this)}}),this.style=Object.freeze(s),this.style.reset(i)}setStyle(e,t){if(null==t&&(t=void 0),j.validate(this.layout,e,t),"color"==e&&t)return this.sheet.red=t.red,this.sheet.green=t.green,this.sheet.blue=t.blue,void(this.sheet.alpha=t.alpha);null==t?delete this.sheet[e]:this.sheet[e]=t}getStyle(e){let t=this.sheet[e];return"visibility"==e?"boolean"!=typeof t&&(t=!0):"color"==e&&B.isColor(this.sheet)&&(t=B.fromColor(this.sheet)),t}getComputed(e){let t=this.getStyle(e);if(null==t)if("color"==e){let e={red:isFinite(this.sheet.red)?this.sheet.red:this.pointProps.red,green:isFinite(this.sheet.green)?this.sheet.green:this.pointProps.green,blue:isFinite(this.sheet.blue)?this.sheet.blue:this.pointProps.blue,alpha:isFinite(this.sheet.alpha)?this.sheet.alpha:this.pointProps.alpha};B.isColor(e)&&(t=B.fromColor(e))}else t=this.pointProps[e];return t}clear(){this.sheet={}}static validate(e,t,i,s){let r;if(i&&e.includes(w.Property[_.getEnumValueName(t)])){if(!s)throw new Error(`Property ${t} value ${i} is not applicable. This is a dynamic property and is part of the layout.`);console.warn(`Property ${t} value ${i} is not applicable. This is a dynamic property and is part of the layout.`),i=void 0}if("color"==t)!i||i instanceof B||(r=`Property ${t} is not an instance of Color`);else if("blendMode"==t)""==i&&(i=void 0);else if("number"==typeof i)if("size"==t)i<0?r=`Property ${t} with value ${i} is not allowed. Value should be a positive number.`:0==i&&(i=void 0);else if("red"==t||"green"==t||"blue"==t||"alpha"==t){let e="alpha"==t?{min:0,max:1}:{min:0,max:255};i>=e.min&&i<=e.max||(r=`Property ${t} with value ${i} is out of range. Allowd range: [${e.min}, ${e.max}].`)}else"rotation"==t?0==i&&(i=void 0):"scattering"==t&&i<0&&(i=void 0);if(r)throw new Error(r);return i}}class ${static encode(e,t=$.Encoding.AUTO){let i;if(t==$.Encoding.AUTO?t="undefined"==typeof Buffer?"undefined"!=typeof SharedArrayBuffer&&e.buffer instanceof SharedArrayBuffer?$.Encoding.NONE:$.Encoding.ARRAY:$.Encoding.BUFFER:t==$.Encoding.ARRAY&&e instanceof Array&&(t=$.Encoding.NONE),t==$.Encoding.NONE)i=e;else if(t==$.Encoding.ARRAY)i=e.toArray();else{if("undefined"==typeof Buffer)throw new Error("Buffer not found, unable to serialize. Please provide Buffer in global scope.");let s=Buffer.from(e.buffer);switch(t){case $.Encoding.BUFFER:i=s.toJSON();break;case $.Encoding.BASE64:i=s.toString("base64");break;default:throw new Error(`Invalid encoding provided: ${t.name}`)}}return{encoding:t.name,type:e.constructor.name,content:i}}static decode(e){let t,i=$.Encoding[e.encoding];if(i==$.Encoding.NONE)t=e.content;else if(i==$.Encoding.ARRAY)t=e.content.toFloat32Array();else{let s;switch(i){case $.Encoding.BUFFER:s="undefined"==typeof Buffer?e.content.data:Buffer.from(e.content);break;case $.Encoding.BASE64:s="undefined"==typeof Buffer?atob(e.content).toCharArray():Buffer.from(e.content,"base64");break;default:throw new Error(`Invalid encoding provided: ${i.name}`)}let r=new Uint8Array(s);t=new globalThis[e.type](r.buffer)}return t}static isTypedArrayData(e){return e&&e.encoding&&e.type&&e.type.endsWith("Array")}}Object.defineEnum($,"Encoding",["AUTO","NONE","ARRAY","BUFFER","BASE64"]);const U=[w.Property.X,w.Property.Y];class Y{#e;#t;constructor(e,t={},i=U){if(this.#e=e,Object.defineProperty(this,"points",{get:()=>this.#e,set:e=>{if(this.#e instanceof Float32Array)throw new Error("Points setter is not accessible wehn points type is Float32Array.");this.#e=e,this.validate()},enumerable:!0}),Object.defineProperty(this,"buffer",{get:()=>this.#e.buffer,set:e=>{if(Array.isArray(this.#e))throw new Error("Underlying points buffer is Array. This property is applicable for TypedArray only.");if("undefined"!=typeof SharedArrayBuffer&&this.#e.buffer instanceof SharedArrayBuffer)throw new Error("Underlying buffer is SharedArrayBuffer and cannot be restored");if(this.#e.buffer.byteLength>0)throw new Error("Cannot restore buffer when underlying buffer is not empty");if(e.byteLength/Float32Array.BYTES_PER_ELEMENT/this.stride!=this.length)throw new Error("Value exceeds expected memory length");this.#e=new Float32Array(e)}}),!Object.isSealed(t))for(let e in t)void 0!==t[e]&&(t[e]=j.validate(i,e,t[e],!0));i.includes(w.Property.ROTATION)||"rotation"in t||(t.rotation=void 0),i.includes(w.Property.SIZE)||t.size||(t.size=1),Object.defineProperties(this,{stride:{value:i.length,enumerable:!0},layout:{value:Object.freeze(i),enumerable:!0},pointProps:{value:Object.seal(t),enumerable:!0}}),e instanceof Float32Array?Object.defineProperty(this,"length",{value:this.#e.length/this.stride,enumerable:!0}):Object.defineProperty(this,"length",{get:()=>this.#e.length/this.stride,enumerable:!0}),i.forEach(((e,t)=>{let i=_.getPropName(e.name,!0);Object.defineProperty(this,`setPoint${i}`,{value:this.setPointPropertyValue.bind(this,t)}),Object.defineProperty(this,`getPoint${i}`,{value:this.getPointPropertyValue.bind(this,t)})}))}validate(){if(this.points.length%this.stride!=0)throw new Error("Path length doesn't match the stride provided via the layout")}setPointPropertyValue(e,t,i){if(isNaN(t))throw new Error("Point index is required");if(t>=this.length||t<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);if(isNaN(i))throw new Error("value is required");this.points[t*this.layout.length+e]=i}getPointPropertyValue(e,t){if(isNaN(t))throw new Error("Point index is required");if(t>=this.length||t<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);return this.points[t*this.layout.length+e]}setPoint(e,t){let i=e*this.stride;this.layout.forEach(((e,s)=>this.points[i+s]=t.getProperty(e)))}getPoint(e,t=this.pointProps){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);return w.createInstance(this.layout,t,this.points,e)}getPointRef(e,t=this.pointProps){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);return this.#t||(this.#t=w.createInstance(this.layout)),this.#t.fill(e,this.points,this.layout,this.pointProps),this.#t}getChannelData(e){let t=new([w.Property.RED,w.Property.GREEN,w.Property.BLUE].includes(e)?Uint8Array:Float32Array)(this.length),i=this.layout.indexOf(e);if(-1==i)throw new Error(`Property ${e.name} is not part from the spline layout ${this.layout.map((e=>e.name)).join(", ")}`);for(let e=0;e<this.length;e++)t[e]=this.points[e*this.stride+i];return t}transform(e){let t=e.scaleX,s=e.rotation;for(let r=0;r<this.length;r++){let n=r*this.stride,a=i.fromValues(this.getPointX(r),this.getPointY(r),0,1);i.transformMat4(a,a,e.value);for(let e=0;e<this.stride;e++){let i=n+e;switch(this.layout[e]){case w.Property.X:this.points[i]=a[0]/a[3];break;case w.Property.Y:this.points[i]=a[1]/a[3];break;case w.Property.Z:this.points[i]=a[2]/a[3];break;case w.Property.ROTATION:this.points[i]+=s;break;case w.Property.SIZE:this.points[i]*=t}}}this.layout.includes(w.Property.ROTATION)||(this.pointProps.rotation=0==s?void 0:s)}clone(){return new Y(this.#e.clone(),Object.clone(this.pointProps),this.layout.slice())}getFragment(e=0,t=this.length-1){return new L(this,e,t)}slice(e){let t=this.slicePoints(e.pointIndexStart,e.pointIndexEnd);return new Y(t,Object.clone(this.pointProps),this.layout.slice())}validateFragment(e,t){if(e<0)throw new Error(`Invalid fragment pointIndexStart ${e} found. The value must be non-negative.`);if(t>this.length-1)throw new Error(`Invalid fragment pointIndexEnd ${t} found. Last point in path index is ${this.length-1}.`)}slicePoints(e,t){let i;if(this.validateFragment(e,t),"undefined"!=typeof SharedArrayBuffer&&this.buffer instanceof SharedArrayBuffer){let s=this.points.subarray(e*this.stride,(t+1)*this.stride),r=new SharedArrayBuffer(s.length*Float32Array.BYTES_PER_ELEMENT);i=new Float32Array(r),i.set(s)}else i=this.points.slice(e*this.stride,(t+1)*this.stride);return i}toSVGPath(){let e=[];for(let t=0;t<this.length;t++)e.push(`${this.getPointX(t)},${this.getPointY(t)}`);return`M ${e.join(" L ")} Z`}toJSON(){return{type:"Path",points:$.encode(this.#e,this.encoding),pointProps:this.pointProps,layout:this.layout.map((e=>e.name))}}static fromJSON(e){if("Path"!=e.type)throw new Error(`Path deserialization failed. JSON type is ${e.type}, expected Path.`);return new Y($.decode(e.points),e.pointProps,e.layout.map((e=>w.Property[e])))}static fromRect(e,t){let i=[e.left,e.top,e.right,e.top,e.right,e.bottom,e.left,e.bottom,e.left,e.top];return new Y(i,t)}static createInstance(e,t,i){return new Y(e,t,i)}static createSharedInstance(e,t,i){return new Y(Float32Array.createSharedInstance(e),t,i)}}class G{constructor(e,t){if(!Array.isArray(e))throw new Error("Unexpected polygons type found");let i=65534/(t.width+1e-16),s=65534/(t.height+1e-16),r=Math.floor(Math.min(i,s));if(0==r)throw new Error(`Insufficent clipper range - (-32767 - 32767), scale failed - scaleX: ${i}, scaleY: ${s}`);let n=t.left+32767/r,a=t.top+32767/r;this.solution=new N,this.bounds=t,this.transform={scale:r,offsetX:n,offsetY:a},this.subject=this.apply(e)}convertPoint(e){let t=(e.x-this.transform.offsetX)*this.transform.scale,i=(e.y-this.transform.offsetY)*this.transform.scale;return{X:t<0?Math.ceil(t):Math.floor(t),Y:i<0?Math.ceil(i):Math.floor(i)}}containsPoint(e){return D.PointInPolygon(this.convertPoint(e),this.solution)}apply(e){let t=new N;for(let i of e){let e=new F,s=i.shape;for(let t=0;t<s.length;t++)e.push(this.convertPoint({x:s.getPointX(t),y:s.getPointY(t)}));t.push(e)}return t}toPaths(){let e=[];this.lastPoint={};for(let t of this.solution){if(0==t.length)continue;let i=this.flatPath(t);i.length>0&&e.push(i)}return e}flatPath(e){let t=[];for(let i of e)this.lastPoint.X==i.X&&this.lastPoint.Y==i.Y||(t.push(i.X/this.transform.scale+this.transform.offsetX,i.Y/this.transform.scale+this.transform.offsetY),this.lastPoint=i);return t.length<6&&(console.warn(`Invalid contour found: [${t.join(", ")}]`),t.clear()),t}}class X{constructor(e=2){this.stride=e}sort(e,t){return this.sortArrayPart(e,0,e.length-this.stride,t),e}partition(e,t,i,s){let r=e[i],n=e[i+1],a=t-this.stride;for(let o=t;o<i;o+=2)s?s(r,n,e[o],e[o+1])&&(a+=this.stride,this.swap(e,a,o)):(r>e[o]||r==e[o]&&n>e[o+1])&&(a+=this.stride,this.swap(e,a,o));return this.swap(e,a+this.stride,i),a+this.stride}swap(e,t,i){let s=e[t],r=e[t+1];return e[t]=e[i],e[t+1]=e[i+1],e[i]=s,e[i+1]=r,e}sortArrayPart(e,t,i,s){if(t<i){let r=this.partition(e,t,i,s);this.sortArrayPart(e,t,r-this.stride,s),this.sortArrayPart(e,r+this.stride,i,s)}}}function z(e,t,i,s,r,n){return(i-e)*(n-t)-(s-t)*(r-e)}function H(e,t,i,s,r,n){let a=e-i,o=r-i,l=a*(n-s)-o*(t-s);l*=l,a=r-i,o=n-s;let h=a*a+o*o;return h>0?Math.sqrt(l/h):Math.sqrt((i-e)*(i-e)+(s-t)*(s-t))}class q{constructor(e=Float32Array){this.ArrayType=e,this.quickSort=new X}monotoneChain(e){if(e.length<=0)return new this.ArrayType;this.quickSort.sort(e);let t=new this.ArrayType(e.length),i=0;for(let s=0;s<e.length;s+=2){for(;i>=4&&z(t[i-4],t[i-3],t[i-2],t[i-1],e[s],e[s+1])<=0;)i-=2;t[i]=e[s],t[i+1]=e[s+1],i+=2}t=t.slice(0,i);let s,r=new this.ArrayType(e.length);i=0;for(let t=e.length-2;t>=0;t-=2){for(;i>=4&&z(r[i-4],r[i-3],r[i-2],r[i-1],e[t],e[t+1])<=0;)i-=2;r[i]=e[t],r[i+1]=e[t+1],i+=2}if(r=r.slice(0,i-2),this.ArrayType==Float32Array){let e=r.length+t.length;s=Float32Array.createSharedInstance(e),s.set(r),s.set(t,r.length)}else s=r.concat(t);return s}}class J{constructor(e,t,i,s){let r=e,n=t,a=e+i,o=t+s;Object.defineProperties(this,{left:{value:r,enumerable:!0},x:{value:e,enumerable:!0},bottom:{value:n,enumerable:!0},y:{value:t,enumerable:!0},right:{value:a,enumerable:!0},top:{value:o,enumerable:!0},width:{value:i,enumerable:!0},height:{value:s,enumerable:!0}})}union(e){if(e&&!(e instanceof J))throw new TypeError("rect must be instance of RectGL");return e?J.ofEdges(Math.min(this.left,e.left),Math.min(this.bottom,e.bottom),Math.max(this.right,e.right),Math.max(this.top,e.top)):this}intersect(e){if(e&&!(e instanceof J))throw new TypeError("rect must be instance of RectGL");if(!e)return null;let t=J.ofEdges(Math.max(this.left,e.left),Math.max(this.bottom,e.bottom),Math.min(this.right,e.right),Math.min(this.top,e.top));return t.width>0&&t.height>0?t:null}ceil(){return J.ofEdges(Math.floor(this.left),Math.floor(this.bottom),Math.ceil(this.right),Math.ceil(this.top))}floor(){return J.ofEdges(Math.ceil(this.left),Math.ceil(this.bottom),Math.floor(this.right),Math.floor(this.top))}transform(e){if(!e)return this;let t=d.fromPoint({x:this.left,y:this.bottom}).transform(e),i=d.fromPoint({x:this.right,y:this.bottom}).transform(e),s=d.fromPoint({x:this.left,y:this.top}).transform(e),r=d.fromPoint({x:this.right,y:this.top}).transform(e),n=Math.min(s.x,r.x,t.x,i.x),a=Math.min(s.y,r.y,t.y,i.y),o=Math.max(s.x,r.x,t.x,i.x),l=Math.max(s.y,r.y,t.y,i.y);return J.ofEdges(n,a,o,l)}toQuad(e){let t;if(e){let i=d.fromPoint({x:this.left,y:this.bottom}).transform(e),s=d.fromPoint({x:this.right,y:this.bottom}).transform(e),n=d.fromPoint({x:this.left,y:this.top}).transform(e),a=d.fromPoint({x:this.right,y:this.top}).transform(e);t=r.fromValues(i.x,i.y,s.x,s.y,n.x,n.y,a.x,a.y)}else t=r.fromValues(this.left,this.bottom,this.right,this.bottom,this.left,this.top,this.right,this.top);return t}toString(){return`gl-rect(${this.x}, ${this.y}, ${this.width}, ${this.height})`}static ofEdges(e,t,i,s){return new J(e,t,i-e,s-t)}static calculateBrushGLSegmentBounds(e,t=0,i){let s,r=.5*e.size,n=Math.abs(t*r);if(i){s=new d(e.x,e.y,e.x,e.z).transform(i)}else s=e;let a=s.x,o=s.y,l=e.scaleX*r,h=e.scaleY*r,u=e.offsetX,p=-e.offsetY,c=Math.cos(e.rotation),f=Math.sin(e.rotation),m=Number.MAX_SAFE_INTEGER,g=Number.MIN_SAFE_INTEGER,y=Number.MAX_SAFE_INTEGER,P=Number.MIN_SAFE_INTEGER;for(let e of J.SQURE){let t=e.x*l+u,i=e.y*h+p,s=c*t+f*i+a,r=-f*t+c*i+o,d=s-n;m=Math.min(m,d),g=Math.max(g,d),d=s+n,m=Math.min(m,d),g=Math.max(g,d);let b=r-n;y=Math.min(y,b),P=Math.max(P,b),b=r+n,y=Math.min(y,b),P=Math.max(P,b)}return J.ofEdges(m,y,g,P)}}Object.defineProperty(J,"SQURE",{value:Object.freeze([Object.freeze({x:-1,y:-1}),Object.freeze({x:1,y:-1}),Object.freeze({x:-1,y:1}),Object.freeze({x:1,y:1})]),enumerable:!0});class V{constructor(e,t,i,s){let r,n,a,o=e,l=t,h=e+i,u=t+s;Object.defineProperties(this,{left:{value:o,enumerable:!0},top:{value:l,enumerable:!0},right:{value:h,enumerable:!0},bottom:{value:u,enumerable:!0},x:{value:e,enumerable:!0},y:{value:t,enumerable:!0},width:{value:i,enumerable:!0},height:{value:s,enumerable:!0},size:{get:()=>(r||(r={width:i,height:s}),r),enumerable:!0},area:{get:()=>(n||(n=i*s),n),enumerable:!0},center:{get:()=>(a||(a={x:(o+h)/2,y:(l+u)/2}),a),enumerable:!0}})}union(e){return e?V.ofEdges(Math.min(this.left,e.left),Math.min(this.top,e.top),Math.max(this.right,e.right),Math.max(this.bottom,e.bottom)):this}intersect(e){if(!e)return null;let t=V.ofEdges(Math.max(this.left,e.left),Math.max(this.top,e.top),Math.min(this.right,e.right),Math.min(this.bottom,e.bottom));return t.width>0&&t.height>0?t:null}intersects(e){return this.left<=e.right&&this.right>=e.left&&this.top<=e.bottom&&this.bottom>=e.top}ceil(e){let t=Math.floor(this.left),i=Math.floor(this.top),s=Math.ceil(this.right),r=Math.ceil(this.bottom);if(e){let e=s-t,n=r-i;e+=e%2,n+=n%2,s=t+e,r=i+n}return V.ofEdges(t,i,s,r)}floor(e){let t=Math.ceil(this.left),i=Math.ceil(this.top),s=Math.floor(this.right),r=Math.floor(this.bottom);if(e){let e=s-t,n=r-i;e-=e%2,n-=n%2,s=t+e,r=i+n}return V.ofEdges(t,i,s,r)}contains(e){return this.left<=e.x&&this.right>=e.x&&this.top<=e.y&&this.bottom>=e.y}includes(e){return this.left<=e.left&&this.right>=e.right&&this.top<=e.top&&this.bottom>=e.bottom}transform(e){if(!e)return this;let t=d.fromPoint({x:this.left,y:this.top}).transform(e),i=d.fromPoint({x:this.right,y:this.top}).transform(e),s=d.fromPoint({x:this.left,y:this.bottom}).transform(e),r=d.fromPoint({x:this.right,y:this.bottom}).transform(e),n=Math.min(t.x,i.x,s.x,r.x),a=Math.min(t.y,i.y,s.y,r.y),o=Math.max(t.x,i.x,s.x,r.x),l=Math.max(t.y,i.y,s.y,r.y);return V.ofEdges(n,a,o,l)}toPath(e,t=1){throw new Error("Rect.toPath is deprecated. Path.fromRect(rect, [pointProps]) instead")}toGLRect(){return new J(this.x,this.y,this.width,this.height)}toString(){return`rect(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toJSON(){return{x:this.left,y:this.top,width:this.width,height:this.height}}static fromGLRect(e){if(!e)return null;if(!(e instanceof J))throw new TypeError("rect must be instance of RectGL");return new V(e.left,e.bottom,e.width,e.height)}static isRect(e){return e&&isFinite(e.left)&&isFinite(e.top)&&isFinite(e.width)&&isFinite(e.height)}static fromString(e){return e=e.substring(e.indexOf("(")+1,e.indexOf(")")).split(/,\s*/g),new V(parseFloat(e[0]),parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]))}static fromRect(e){return"string"==typeof e?V.fromString(e):new V(e.x,e.y,e.width,e.height)}static ofPolygon(e){if(e.shape&&(e=e.shape),0==e.length)return null;let t=Number.MAX_SAFE_INTEGER,i=Number.MAX_SAFE_INTEGER,s=Number.MIN_SAFE_INTEGER,r=Number.MIN_SAFE_INTEGER;for(let n=0;n<e.length;n++){let a=e.getPointX(n),o=e.getPointY(n);t=Math.min(t,a),i=Math.min(i,o),s=Math.max(s,a),r=Math.max(r,o)}return V.ofEdges(t,i,s,r)}static ofSpline(e,t=0){let i;for(let s=0;s<e.length;s++)i=J.calculateBrushGLSegmentBounds(e.getPointRef(s),t).union(i);return V.fromGLRect(i)}static ofEdges(e,t,i,s){let r=Math.min(e,i),n=Math.min(t,s),a=Math.max(e,i),o=Math.max(t,s);return new V(r,n,a-r,o-n)}static union(e,t){return e?t?e.union(t):e:t}static intersect(e,t){return e&&t?e.intersect(t):null}}class W{constructor(e,t=[]){if(!(e instanceof Y))throw new Error("Expected shape type is Path. Use createInstance or createSharedInstance Polygon methods to allocate instance.");if(t.some((e=>!(e instanceof Y))))throw new Error("Expected hole type is Path. Use createInstance or createSharedInstance Polygon methods to allocate instance.");let i;this.holesDirection=W.PointsDirection.CLOCKWISE,Object.defineProperty(this,"shape",{value:e,enumerable:!0}),Object.defineProperty(this,"holes",{value:t,enumerable:!0}),Object.defineProperty(this,"contours",{value:[e,...t],enumerable:!0}),Object.defineProperty(this,"ArrayType",{value:e.points instanceof Float32Array?Float32Array:Array}),Object.defineProperty(this,"bounds",{get:()=>V.ofPolygon(this),enumerable:!0}),Object.defineProperty(this,"vertices",{get:()=>(i||(i=this.triangulate()),i),set:e=>i=e,enumerable:!0}),Object.defineProperty(this,"verticesValue",{get:()=>i})}clone(e=!1){let t=this.shape.clone(e),i=this.holes.map((t=>t.clone(e))),s=new W(t,i);return this.verticesValue&&(s.vertices=this.vertices.slice()),s}fit(e){let t=this.bounds,i=e.width/t.width,s=e.height/t.height,r=i>0&&s>0?Math.min(i,s):Math.max(i,s);for(let e of this.contours)for(let t=0;t<e.length;t++)e.setPointX(t,e.getPointX(t)*r),e.setPointY(t,e.getPointY(t)*r)}center(){let e=this.bounds;for(let t of this.contours)for(let i=0;i<t.length;i++)t.setPointX(i,t.getPointX(i)-e.center.x),t.setPointY(i,t.getPointY(i)-e.center.y)}transform(e){this.contours.forEach((t=>t.transform(e)))}intersects(e){if(!(e instanceof W))throw new Error("Expected 'poly' type is Polygon");(this.holes.length>0||e.holes.length)&&console.warn("Polygon intersection is for contours only. Holes are ignored.");let t=this.shape,i=e.shape;for(let e=0;e<2;e++){let s=0==e?t:i;for(let e=0;e<s.length;e++){let r=e+1==s.length?0:e+1,n=s.getPointX(e),a=s.getPointY(e),o=s.getPointX(r),l=s.getPointY(r)-a,h=n-o,u=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let e=0;e<t.length;e++){let i=l*t.getPointX(e)+h*t.getPointY(e);i<u&&(u=i),i>p&&(p=i)}let c=Number.POSITIVE_INFINITY,d=Number.NEGATIVE_INFINITY;for(let e=0;e<i.length;e++){let t=l*i.getPointX(e)+h*i.getPointY(e);t<c&&(c=t),t>d&&(d=t)}if(p<c||d<u)return!1}}return!0}containsPoint(e){let t=!1,i=this.shape;this.holes.length>0&&console.warn("Polygon intersection is for contours only. Holes are ignored.");for(let s=0,r=i.length-1;s<i.length;r=s++)i.getPointY(s)>e.y!=i.getPointY(r)>e.y&&e.x<(i.getPointX(r)-i.getPointX(s))*(e.y-i.getPointY(s))/(i.getPointY(r)-i.getPointY(s))+i.getPointX(s)&&(t=!t);return t}triangulate(){let e,t=[];for(let e of this.contours){let i=[];for(let t=0;t<e.length;t++){let s=new R(e.getPointX(t),e.getPointY(t));if(t>0){if(i.last.x==s.x&&i.last.y==s.y)continue;if(t==e.length-1&&i.first.x==s.x&&i.first.y==s.y)continue}i.push(s)}t.push(i)}try{e=new A(t.shift())}catch(e){return console.error(e),new Float32Array}for(let i of t)try{e.addHole(i)}catch(e){return console.error(e),new Float32Array}try{e.triangulate()}catch(e){return console.warn(e),new Float32Array}let i=e.getTriangles(),s=Float32Array.createSharedInstance(6*i.length),r=0;for(let e of i){let t=e.getPoints();for(let e of t)s[r++]=e.x,s[r++]=e.y}return s}convex(){return this.buildConvex(this.shape.points)}union(e){let t=Array.of(...this.shape.points,...e.shape.points);return this.buildConvex(t)}buildConvex(e){this.convexHullProducer||(this.convexHullProducer=new q(this.ArrayType));let t=this.convexHullProducer.monotoneChain(e);return this.ArrayType==Float32Array?W.createSharedInstance(t):W.createInstance(t)}simplify(e=.1){let t=new G([this],this.bounds);return t.subject=D.SimplifyPolygons(t.subject,k.pftNonZero),t.solution=D.CleanPolygons(t.subject,e*t.transform.scale),1==t.subject.length&&0==t.solution.first.length&&(t.solution=t.subject),W.toPolygonArray(t.toPaths())}simplifyRamerDouglasPeucker(e=.1){if(e<=0)throw new Error("epsilon expected value > 0");this.epsilon=e;let t=this.simplifyPath(this.shape),i=[];for(let e of this.holes){let t=this.simplifyPath(e);t.length>0&&i.push(t)}return this.ArrayType==Float32Array?W.createSharedInstance(t,i):W.createInstance(t,i)}simplifyPath(e){if(e.length<3)return e.points;let t=Array.of(...e.points,e.getPointX(0),e.getPointY(0)),i=this.simplifyPolyline(t);return i.length<8?t.slice(0,t.length-2):i.slice(0,i.length-2)}simplifyPolyline(e){if(e.length<4)return e;let t=0,i=0;for(let s=2;s<e.length-2;s+=2){let r=H(e[s],e[s+1],e[0],e[1],e[e.length-2],e[e.length-1]);r>t&&(i=s,t=r)}if(t>this.epsilon){let t=this.simplifyPolyline(e.slice(0,i+2)),s=this.simplifyPolyline(e.slice(i,e.length));return t.concat(s.slice(2,s.length))}return[e[0],e[1],e[e.length-2],e[e.length-1]]}toSVGPath(){return this.contours.map((e=>e.toSVGPath())).join(" ")}toJSON(){return{type:"Polygon",shape:this.shape.toJSON(),holes:this.holes.map((e=>e.toJSON())),holesDirection:this.holesDirection.name,vertices:this.verticesValue}}static fromJSON(e){if("Polygon"!=e.type)throw new Error(`Polygon deserialization failed. JSON type is ${e.type}, expected Polygon.`);let t=Y.fromJSON(e.shape),i=e.holes.map((e=>Y.fromJSON(e))),s=new W(t,i);return s.holesDirection=W.PointsDirection[e.holesDirection],s.vertices=e.vertices,s}static fromRect(e){return W.createInstance([e.left,e.top,e.right,e.top,e.right,e.bottom,e.left,e.bottom,e.left,e.top])}static createInstance(e,t=[]){return new W(Y.createInstance(e),t.map((e=>Y.createInstance(e))))}static createSharedInstance(e,t=[]){let i=new W(Y.createSharedInstance(e),t.map((e=>Y.createSharedInstance(e))));return Object.defineProperty(i,"encoding",{get:()=>i.shape.encoding,set:e=>{i.contours.forEach((t=>t.encoding=e))},enumerable:!0}),i}}Object.defineEnum(W,"PointsDirection",["CLOCKWISE","COUNTERCLOCKWISE"]);class Z{static ARRAY_TYPE=Array;#i;constructor(){this.keepAllData=!1,Object.defineProperty(this,"allData",{get:()=>{if(!this.keepAllData)throw new Error("All data is not accumulated. By default keepAllData property is false.");return this.#i||(this.#i=new this.constructor.ARRAY_TYPE),this.getOutput(this.#i,Z.OutputType.ALL_DATA)},enumerable:!0})}build(e,t=Z.OutputType.PROCESSOR,i=!0){return console.warn("use process instead"),this.process(e,t,i)}process(e,t=Z.OutputType.PROCESSOR,i=!0){let s;switch(t){case Z.OutputType.ADDITION:s=this.add(e,i);break;case Z.OutputType.PREDICTION:s=this.predict(e);break;case Z.OutputType.PROCESSOR:this.reset(),s=this.processImpl(e,t);break;default:throw new Error("Unexpected OutputType found. Allowed type is oneof(ADDITION, PREDICTION, PROCESSOR)")}return t!=Z.OutputType.PREDICTION&&this.keepAllData&&(this.#i||(this.#i=new this.constructor.ARRAY_TYPE),s instanceof W?this.#i.push(s):t==Z.OutputType.PROCESSOR?this.#i=s:this.#i.push(...s)),this.debug&&console.log(this.constructor.name,t.name,i,s),this.getOutput(s,t)}add(e,t=!1){return this.processImpl(e,Z.OutputType.ADDITION)}predict(e){return this.processImpl(e,Z.OutputType.PREDICTION)}processImpl(e,t){throw new Error("Abstract method processImpl(input, type) of DataSequenceProcessor should be implemented")}getOutput(e,t){return e}reset(){this.#i&&(this.#i=new this.constructor.ARRAY_TYPE)}}Object.defineEnum(Z,"OutputType",["ADDITION","PREDICTION","ALL_DATA","PROCESSOR"]);let K=h?h.default||globalThis.md5:{},Q={mask:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",generate(){let e=Date.now();return this.mask.replace(/[xy]/g,(function(t){let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))},validate:e=>"string"==typeof e&&!!e.match(/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/),format(e){let t=[],i=0;return this.mask.split("-").forEach((s=>{t.push(e.substring(i,i+s.length)),i+=s.length})),t.join("-")},fromString(e){return this.fromBytes(new Uint8Array(K.arrayBuffer(e)))},toBytes(e){let t=[];return e.split("-").map(((e,i)=>{(i<3?e.match(/.{1,2}/g).reverse():e.match(/.{1,2}/g)).map((e=>t.push(parseInt(e,16))))})),new Uint8Array(t)},fromBytes(e){let t=Array.from(e).map((e=>e.toString(16))).map((e=>(1==e.length?"0":"")+e));return t.slice(0,4).reverse().join("")+"-"+t.slice(4,6).reverse().join("")+"-"+t.slice(6,8).reverse().join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10).join("")},toUint32Array(e){let t=new Uint32Array(4),i=this.toBytes(e);return t[0]=new Uint32Array(i.slice(0,4).buffer)[0],t[1]=new Uint32Array(i.slice(4,8).buffer)[0],t[2]=new Uint32Array(i.slice(8,12).buffer)[0],t[3]=new Uint32Array(i.slice(12).buffer)[0],t},fromUint32Array(e){return this.fromBytes(new Uint8Array(e.buffer))},toUint64Array(e){let t=new BigUint64Array(2),i=this.toBytes(e);return t[0]=new BigUint64Array(i.slice(0,8).buffer)[0],t[1]=new BigUint64Array(i.slice(8).buffer)[0],t},fromUint64Array(e){return this.fromBytes(new Uint8Array(e.buffer))},toLongArray(e){let t=new Array(2),i=this.toBytes(e);return t[0]=l.fromBytes(i.slice(0,8)),t[1]=l.fromBytes(i.slice(8)),t},fromLongArray(e){let t=e[0].toBytes().concat(e[1].toBytes());return this.fromBytes(t)}};class ee{#s;constructor(e,t,i,s,r){1==i&&(t++,i=0),0==r&&(s--,r=1),Object.defineProperties(this,{spline:{value:e,enumerable:!0},segmentIndexStart:{value:t,enumerable:!0},segmentIndexEnd:{value:s,enumerable:!0},ts:{value:i,enumerable:!0},tf:{value:r,enumerable:!0}}),Object.defineProperty(this,"pointIndexStart",{value:t,enumerable:!0}),Object.defineProperty(this,"pointIndexEnd",{value:s+3,enumerable:!0}),Object.defineProperty(this,"length",{value:this.pointIndexEnd-this.pointIndexStart+1,enumerable:!0}),Object.defineProperty(this,"id",{get:()=>(this.#s||(this.#s=Q.generate()),this.#s),set:e=>{if(this.#s)throw new Error("id is immutable");this.#s=e}}),this.validate()}validate(){let e=this.length-3;if(this.pointIndexStart<0)throw new Error(`Invalid fragment pointIndexStart ${this.pointIndexStart} found. The value must be non-negative.`);if(this.pointIndexEnd>this.spline.length-1)throw new Error(`Invalid fragment pointIndexEnd ${this.pointIndexEnd} found. Last point in spline index is ${this.spline.length-1}.`);if(this.ts<0||this.ts>=1)throw new Error(`Invalid fragment ts ${this.ts} found. The value must be in the interval [0, 1).`);if(this.tf<=0||this.tf>1)throw new Error(`Invalid fragment tf ${this.tf} found. The value must be in the interval (0, 1].`);if(e<1)throw new Error(`Invalid fragment points range {${this.pointIndexStart}, ${this.pointIndexEnd}} found. At least 4 points are needed to define spline.`);if(1==e&&this.ts>this.tf)throw new Error(`Invalid fragment T range ${this.ts} - ${this.tf} found. Spline has only one segment and ts <= tf.`)}union(e){let t=[this,e];t.sort(ee.compare);let i=t.first,s=t.last,r=i.segmentIndexEnd,n=i.tf;if(1==n&&(r++,n=0),r!=s.segmentIndexStart||n!=s.ts)throw new Error(`Fragments ${i} and ${s} are not adjacent.`);let a=new ee(this.spline,i.segmentIndexStart,i.ts,s.segmentIndexEnd,s.tf);return a.#s=this.#s,this.inside&&(a.inside=this.inside),a}overlaps(e){if(e.spline!=this.spline)return!1;let t=e.segmentIndexStart<this.segmentIndexEnd||e.segmentIndexStart==this.segmentIndexEnd&&e.ts<=this.tf,i=e.segmentIndexEnd>this.segmentIndexStart||e.segmentIndexEnd==this.segmentIndexStart&&e.tf>=this.ts;return t&&i}toString(){return`fragment(${this.segmentIndexStart}, ${this.ts} - ${this.segmentIndexEnd}, ${this.tf})`}static compare(e,t){return e.segmentIndexStart<t.segmentIndexStart?-1:e.segmentIndexStart>t.segmentIndexStart?1:e.ts<t.ts?-1:e.ts>t.ts?1:0}static getInstance(e,t,i){return new ee(e,t.segmentIndex,t.t,i.segmentIndex,i.t)}}class te extends Y{constructor(e,t,i,s=[]){super(t,i,e),s.length>0&&!Object.isFrozen(s.first)&&s.forEach((e=>Object.freeze(e))),Object.defineProperty(this,"splineParameters",{value:Object.freeze(s),enumerable:!0});let r=new j(e,i);Object.defineProperty(this,"style",{get:()=>r.style,set:e=>r.style.reset(e),enumerable:!0}),Object.defineProperty(this,"color",{get:()=>this.style.color,set:e=>{if(!e)throw new Error("Spline color cannot be removed");if(!(e instanceof B))throw new Error("Expected value should be Color instance");"red"in this.pointProps&&(this.pointProps.red=e.red),"green"in this.pointProps&&(this.pointProps.green=e.green),"blue"in this.pointProps&&(this.pointProps.blue=e.blue),"alpha"in this.pointProps&&(this.pointProps.alpha=e.alpha)},enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>V.ofSpline(this,this.pointProps.scattering).ceil(),enumerable:!0}),this.validate()}validate(){let e=this.points instanceof Float32Array;if(super.validate(),!this.layout.includes(w.Property.X))throw new Error("Layout doesn't contains required properties X");if(!this.layout.includes(w.Property.Y))throw new Error("Layout doesn't contains required properties Y");if(e&&0==this.points.length)throw new Error("Empty spline is not allowed")}clone(){return new te(this.layout.slice(),this.points.clone(),Object.clone(this.pointProps),this.splineParameters.slice())}slice(e){let t=this.slicePoints(e.pointIndexStart,e.pointIndexEnd);return new te(this.layout.slice(),t,Object.clone(this.pointProps),this.splineParameters.slice())}getPoint(e){return super.getPoint(e,this.style)}getPointRef(e){return super.getPointRef(e,this.style)}getPointSegmentIndex(e){return this.splineParameters[e]?this.splineParameters[e].index:void 0}getPointT(e){return this.splineParameters[e]?this.splineParameters[e].t:void 0}getPointParameter(e){return this.splineParameters[e]}toJSON(){return{type:"InterpolatedSpline",layout:this.layout.map((e=>e.name)),points:$.encode(this.points,this.encoding),pointProps:this.pointProps,splineParameters:this.splineParameters}}static fromJSON(e){let t=$.decode(e.points);return new te(e.layout.map((e=>w.Property[e])),t,e.pointProps,e.splineParameters.map(p.fromJSON))}static fromRect(e,t){throw new Error("InterpolatedSpline.fromRect is not supported. Try Spline.fromRect and interpolate with particular Spline interpolator.")}static createInstance(e,t,i=[]){return new te(e,i,t)}static createSharedInstance(e,t,i,s){return new te(e,Float32Array.createSharedInstance(t),i,s)}}const ie=s.fromValues(0,-.5,1,-.5,1,0,-2.5,1.5,0,.5,2,-1.5,0,0,-.5,.5);class se extends Z{#r;#n;#a;constructor(e=!1,t=!1){super(),this.calculateDerivates=e,this.keepSplineParameters=t,this.state={segmentIndex:-1,lastPointPosition:void 0,lastPointSize:0}}initState(e){this.state.layout={},e.layout.forEach(((e,t)=>{this.state.layout[e.name]={index:t,polynomials:i.create()}})),this.keepSplineParameters?this.state.splineParameters?this.state.splineParameters.clear():this.state.splineParameters=[]:delete this.state.splineParameters,this.splineLayout=e.layout,this.pathPointProps=Object.clone(e.pointProps),this.scattering&&(this.pathPointProps.scattering=this.scattering),this.layout=this.calculateDerivates?e.layout.concat([w.Property.D_X,w.Property.D_Y]):e.layout,this.state.ready=!0}predict(e){if(!e)return[];this.state.ready||this.initState(e),this.#n?this.#n.points.clear():this.#n=te.createInstance(this.layout,this.pathPointProps),this.path=this.#n;let t=Object.clone(this.state);return delete this.state.splineParameters,this.resetState(),this.discretize(e),this.state=t,this.path.points}processImpl(e,t){if(!e)return[];let i;return e instanceof ee&&(i=e,e=i.spline),this.state.ready||this.initState(e),t==se.OutputType.ADDITION?(this.#r?this.#r.points.clear():this.#r=te.createInstance(this.layout,this.pathPointProps),this.path=this.#r):(this.#a=te.createInstance(this.layout,this.pathPointProps),this.path=this.#a),this.discretize(e,i),this.path.points}getOutput(e,t){if(0!=e.length){if(t==se.OutputType.PROCESSOR||t==se.OutputType.ALL_DATA){let t=this.state.splineParameters;return t&&(t=t.slice()),te.createSharedInstance(this.layout,e,this.pathPointProps,t)}return this.path}}calculateInterpolatedPoint(e,t,s){this.initState(e);let r=new w(0,0,this.splineLayout.includes(w.Property.Z)?0:void 0),n=i.fromValues(1,s,s*s,s*s*s);return this.calculatePolynomials(e,t),this.splineLayout.forEach((e=>{let t=i.dot(this.state.layout[e.name].polynomials,n);r[_.getPropName(e.name)]=t})),r}discretize(e,t){throw new Error("This method is abstract and should be implemented")}storeLastPoint(e,t=0){this.state.lastPointPosition=new d(this.getPropValue(w.Property.X,e,t),this.getPropValue(w.Property.Y,e,t),this.getPropValue(w.Property.Z,e,t)),this.state.lastPointSize=this.getPropValue(w.Property.SIZE,e,t)}getPropValue(e,t,i=0){return this.state.layout[e.name]?t[i+this.state.layout[e.name].index]:void 0}calculatePolynomials(e,t){let s=e.points,r=this.splineLayout.length*(t+0),n=this.splineLayout.length*(t+1),a=this.splineLayout.length*(t+2),o=this.splineLayout.length*(t+3);this.splineLayout.forEach(((e,t)=>{let l=i.fromValues(s[r+t],s[n+t],s[a+t],s[o+t]);i.transformMat4(this.state.layout[e.name].polynomials,l,ie)}))}samplePoint(e){let t=[],s=i.fromValues(1,e,e*e,e*e*e);return this.splineLayout.forEach((e=>{let r=i.dot(this.state.layout[e.name].polynomials,s);t.push(r)})),this.calculateDerivates&&(t.push(this.getDerivativeOf(this.state.layout.X.polynomials,s)),t.push(this.getDerivativeOf(this.state.layout.Y.polynomials,s))),t}getDerivativeOf(e,t){let s=i.fromValues(e[1],2*e[2],3*e[3],0);return i.dot(s,t)}keepSegmentT(e){this.state.splineParameters&&this.state.splineParameters.push(new p(this.state.segmentIndex,e))}resetState(){this.state.segmentIndex=-1}reset(){super.reset(),this.state.ready=!1,this.state.lastPointPosition=void 0,this.state.lastPointSize=0,this.resetState(),this.#r=null,this.#n=null,this.#a=null}}class re extends se{constructor(e,t){super(e,t),this.state.lastSegmentIndex=-1,this.state.lastPointRotation=0,this.state.lastPointT=0,this.state.absAccumulatedErrorPos=0,this.state.absAccumulatedErrorS=0,this.setT=new v,this.samples=[],Object.defineProperty(this,"errorThreshold",{get:()=>this.error,set:e=>{this.error=e,this.errorDistSq=this.error*this.error,this.error10=10*this.error},enumerable:!0}),this.errorThreshold=.15}discretize(e,t){let i=this.path.points,s=0,r=e.segmentsCount-1,n=e.ts,a=e.tf;t&&(s=t.segmentIndexStart,r=t.segmentIndexEnd,n=t.ts,a=t.tf,this.state.segmentIndex=s-1);for(let t=s;t<r+1;t++){this.state.segmentIndex++,this.calculatePolynomials(e,t);let s=this.calculateTValues(t==r,n,a);i.push(...this.samplePoints(s)),s.length>0&&(this.resetAccumulatedErrors(),this.storeLastPoint(i))}}samplePoints(e){return this.samples.clear(),e.toArray().forEach((e=>{this.keepSegmentT(e),this.samples.push(...this.samplePoint(e))})),this.samples}storeLastPoint(e){let t=e.length-this.layout.length;super.storeLastPoint(e,t),this.state.lastPointRotation=this.getPropValue(w.Property.ROTATION,e,t),this.state.lastPointT=this.setT.max(),this.state.lastSegmentIndex=this.state.segmentIndex}calculateTValues(e,t,i){let s=0==this.state.segmentIndex?t:0,r=e?i:1;return this.setT.clear(),this.getTForPos(s,r),this.state.layout.SIZE&&this.getTForCubic(s,r,this.state.layout.SIZE.polynomials,this.error),this.mustAddStartT()&&this.setT.add(s),e&&this.setT.add(r),this.state.layout.ROTATION&&this.getTForRotation(s,r),this.setT}mustAddStartT(){if(this.state.lastSegmentIndex<0)return!0;let e=this.state.lastPointT-(this.state.segmentIndex-this.state.lastSegmentIndex),t=this.setT.length>0?this.setT.min():1,i=this.getPosErrorAtT0(t,this.state.lastPointPosition);if(this.state.absAccumulatedErrorPos+=Math.abs(i),this.state.layout.SIZE){let i=this.getErrorAtT0(this.state.layout.SIZE.polynomials,t,e,this.state.lastPointSize);this.state.absAccumulatedErrorS+=Math.abs(i)}return this.state.absAccumulatedErrorPos>this.errorDistSq||this.state.absAccumulatedErrorS>this.error}getPosErrorAtT0(e,t){let i=this.getTPoint(e),s=this.getTPoint(0);return this.minDistanceSq(t,i,s)}getErrorAtT0(e,t,i,s){let r=i,n=s,a=t,o=this.cubicCalc(e,a),l=this.cubicCalc(e,0),h=n+(0-r)*(o-n)/(a-r);return Math.abs(l-h)}getTForPos(e,t){let i=this.getTPoint(e),s=this.getTPoint(t),r=this.subdividePos(i,s);if(r.split)this.subdivideRecursivePos(i,r),this.setT.add(r.t),this.subdivideRecursivePos(r,s);else{let e=this.subdividePos(i,r),t=this.subdividePos(r,s);e.split&&(this.subdivideRecursivePos(i,e),this.setT.add(e.t),this.subdivideRecursivePos(e,r)),(e.split||t.split)&&this.setT.add(r.t),t.split&&(this.subdivideRecursivePos(r,t),this.setT.add(t.t),this.subdivideRecursivePos(t,s))}}subdivideRecursivePos(e,t){let i=this.subdividePos(e,t);i.split&&(this.subdivideRecursivePos(e,i),this.setT.add(i.t),this.subdivideRecursivePos(i,t))}subdividePos(e,t){let i=.5*(e.t+t.t),s=this.getTPoint(i),r=this.minDistanceSq(e,t,s),n=e.add(t).scaleSelf(.5),a=s.subtract(n).absSelf();return s.split=r>this.errorDistSq||a.x>this.error10||a.y>this.error10,this.state.layout.Z&&(s.split=s.split||a.z>this.error10),s}getTForCubic(e,t,i,s){let r={v:this.cubicCalc(i,e),t:e},n={v:this.cubicCalc(i,t),t:t},a=this.subdivide(r,n,i);if(a.diff>s)this.subdivideRecursive(r,a,i,s),this.setT.add(a.t),this.subdivideRecursive(a,n,i,s);else{let e=this.subdivide(r,a,i),t=this.subdivide(a,n,i);e.diff>s&&(this.subdivideRecursive(r,e,i,s),this.setT.add(e.t),this.subdivideRecursive(e,a,i,s)),(e.diff>s||t.diff>s)&&this.setT.add(a.t),t.diff>s&&(this.subdivideRecursive(a,t,i,s),this.setT.add(t.t),this.subdivideRecursive(t,n,i,s))}}subdivideRecursive(e,t,i,s){let r=this.subdivide(e,t,i);r.diff>s&&(this.subdivideRecursive(e,r,i,s),this.setT.add(r.t),this.subdivideRecursive(r,t,i,s))}subdivide(e,t,i){let s=.5*(e.t+t.t),r=this.cubicCalc(i,s),n=.5*(e.v+t.v);return{v:r,t:s,diff:Math.abs(r-n)}}getTForRotation(e,t){let i=this.state.layout.ROTATION.polynomials,s=this.state.lastPointRotation;this.state.lastSegmentIndex<0&&(s=this.cubicCalc(i,e));let r=.25*(t-e);for(let t=0;t<4;t++){let n=e+t*r,a=this.cubicCalc(i,n);Math.abs(a-s)>.06&&(this.setT.add(n),s=a)}}minDistanceSq(e,t,i){let s=i.vec,r=s.squaredDistance(e.value,t.value);if(0==r)return s.squaredDistance(i.value,e.value);let n=Math.max(0,Math.min(1,s.dot(i.subtract(e).value,t.subtract(e).value)/r)),a=t.subtract(e).scale(n).add(e);return s.squaredDistance(i.value,a.value)}getTPoint(e){let t=new d(this.cubicCalc(this.state.layout.X.polynomials,e),this.cubicCalc(this.state.layout.Y.polynomials,e),this.state.layout.Z?this.cubicCalc(this.state.layout.Z.polynomials,e):void 0);return t.t=e,t}cubicCalc(e,t){return e[0]+e[1]*t+e[2]*t*t+e[3]*t*t*t}resetAccumulatedErrors(){this.state.absAccumulatedErrorPos=0,this.state.absAccumulatedErrorS=0}resetState(){super.resetState(),this.state.lastSegmentIndex=-1,this.state.lastPointT=0,this.state.lastPointRotation=0,this.resetAccumulatedErrors()}}class ne extends Y{constructor(e,t,i,s=0,r=1){super(t,i,e),this.points instanceof Float32Array?Object.defineProperty(this,"segmentsCount",{value:this.length-3,configurable:!0}):Object.defineProperty(this,"segmentsCount",{get:()=>this.length-3,configurable:!0}),this.ts=s,this.tf=r,Object.defineProperty(this,"bounds",{get:()=>V.ofSpline(this,this.pointProps.scattering).ceil(),enumerable:!0}),Object.defineProperty(this,"color",{get:()=>B.isColor(this.pointProps)?B.fromColor(this.pointProps):void 0,set:e=>{if(!e)throw new Error("Spline color cannot be removed");if(!(e instanceof B))throw new Error("Expected value should be Color instance");"red"in this.pointProps&&(this.pointProps.red=e.red),"green"in this.pointProps&&(this.pointProps.green=e.green),"blue"in this.pointProps&&(this.pointProps.blue=e.blue),"alpha"in this.pointProps&&(this.pointProps.alpha=e.alpha)},enumerable:!0}),this.validate()}validate(){let e=this.points instanceof Float32Array;if(super.validate(),!this.layout.includes(w.Property.X))throw new Error("Layout doesn't contains required properties X");if(!this.layout.includes(w.Property.Y))throw new Error("Layout doesn't contains required properties Y");if(e&&0==this.points.length)throw new Error("Empty spline is not allowed");if(this.ts<0||this.ts>=1)throw new Error(`Invalid spline ts ${this.ts} found. The value must be in the interval [0, 1).`);if(this.tf<=0||this.tf>1)throw new Error(`Invalid spline tf ${this.tf} found. The value must be in the interval (0, 1].`);if(1==this.segmentsCount&&this.ts>this.tf)throw new Error(`Invalid spline t range ${this.ts} - ${this.tf} found. Spline has only one segment and ts <= tf.`);if(e&&this.segmentsCount<1)throw new Error("Incompleted spline found. Spline is defined with at least 4 control points.")}clone(){return new ne(this.layout.slice(),this.points.clone(),Object.clone(this.pointProps),this.ts,this.tf)}slice(e){let t=this.slicePoints(e.pointIndexStart,e.pointIndexEnd),i=new ne(this.layout.slice(),t,Object.clone(this.pointProps),e.ts,e.tf);return i.id=e.id,i}getSegment(e){let t=e,i=e+3,s=0==t?this.ts:0,r=i+1==this.length?this.tf:1;return this.slice({pointIndexStart:t,pointIndexEnd:i,ts:s,tf:r})}getFragment(e=0,t=this.ts,i=this.segmentsCount-1,s=this.tf,r=!1){return new ee(this,e,t,r?i-3:i,s)}toPlainPath(){let e=new Y([]);for(let t=0;t<this.length;t++)e.points.push(this.getPointX(),this.getPointY());return e}toJSON(){return{type:"Spline",id:this.id,layout:this.layout.map((e=>e.name)),points:$.encode(this.points,this.encoding),pointProps:this.pointProps,ts:this.ts,tf:this.tf}}static fromJSON(e){let t=$.decode(e.points),i=new ne(e.layout.map((e=>w.Property[e])),t,e.pointProps,e.ts,e.tf);return i.id=e.id,i}static fromRect(e,t){let i=[e.left,e.top,e.left,e.top,e.right,e.top,e.right,e.bottom,e.left,e.bottom,e.left,e.top,e.left,e.top];return new ne(void 0,i,t)}static createInstance(e,t,i=[],s,r){return new ne(e,i,t,s,r)}static createSharedInstance(e,t,i,s,r){return new ne(e,Float32Array.createSharedInstance(t),i,s,r)}}class ae{constructor(){this.phase=ae.Phase.END}add(e,t,i){if(!this.move(e))throw new Error(`Cannot move from phase ${this.phase.name} to phase ${e.name}`);return this.debug&&(console.log("-------------------------------------"),console.log(this.constructor.name,e.name)),this.addImpl(t,i)}addImpl(e,t){throw new Error("Abstract method addImpl of DataProcessor should be implemented")}move(e){return(this.phase!=ae.Phase.END||e==ae.Phase.BEGIN)&&((this.phase!=ae.Phase.BEGIN||e==ae.Phase.UPDATE||e==ae.Phase.END)&&((this.phase!=ae.Phase.UPDATE||e==ae.Phase.UPDATE||e==ae.Phase.END)&&(e==ae.Phase.BEGIN&&this.reset(),this.phase=e,!0)))}reset(){this.phase=ae.Phase.END}}Object.defineEnum(ae,"Phase",["BEGIN","UPDATE","END"]);class oe extends ae{constructor(e,t){super(),this.layout=e,this.pathPointCalculator=t,this.inputBuffer=[],this.prediction=!0}togglePrediction(e){console.warn("PathProducer togglePrediction method is deprecated. Use InkBuilder instance prediction property to configure prediction behaviour."),this.prediction=e}addImpl(e,t){if(e.phase!=this.phase)throw new Error(`The phase of the addition (${e.phase.name}) doesn't match the phase of the PathProducer (${this.phase.name})`);let i=[],s=[];e&&this.inputBuffer.push(e);let r=this.inputBuffer.length>=3?this.inputBuffer[this.inputBuffer.length-3]:null,n=this.inputBuffer.length>=2?this.inputBuffer[this.inputBuffer.length-2]:null,a=this.inputBuffer.length>=1?this.inputBuffer[this.inputBuffer.length-1]:null,o=this.calculate(r,n,a);return e&&o&&i.push(...o.toArray(this.layout)),this.phase==ae.Phase.END?(o=this.calculate(n,a,null),o&&i.push(...o.toArray(this.layout))):this.prediction&&(this.phase==ae.Phase.UPDATE||t)&&(o=this.calculate(n,a,t),o&&(s.push(...o.toArray(this.layout)),o=this.calculate(a,t,null),o&&s.push(...o.toArray(this.layout)))),{added:i,predicted:s}}calculate(e,t,i){return t?this.pathPointCalculator(e,t,i):null}reset(){super.reset(),this.inputBuffer.clear()}}const le=[-6e-6,-139e-6,-185e-6,414e-6,.002357,.003357,-.003135,-.023928,-.042909,-.017858,.096525,.254692,.347072,.26881,.114933];class he extends Z{#o=[];#l=0;constructor(e,t=15){super(),this.filter=le.slice(),Object.defineProperty(this,"movingAverageWindowSize",{get:function(){return t},set:function(e){t=e,this.filter.length!=e&&(this.filter=he.resample(le,e)),this.predictionPointsCount=4*e/15,this.windowSize=this.filter.length},enumerable:!0}),this.dimsCount=e,this.movingAverageWindowSize=t}add(e,t){return t?this.project(e):this.addSequence(e)}processImpl(e){return this.project(e)}project(e){if(e.length%this.dimsCount!=0)throw new Error(`Points size ('${e.length}') must be multiple of the dimensions count ('${this.dimsCount}').`);if(0==e.length)return[];let t=[],i=this.#o.slice(),s=e.slice(0,e.length-this.dimsCount),r=this.addSequence(s);t.push(...r);let n=e.slice(e.length-this.dimsCount,e.length),a=this.predictionPointsCount;for(let e=0;e<a;e++){let i=this.addPoint(n);a-e<=this.#l&&t.push(...i)}return this.#o=i,t}addSequence(e){if(e.length%this.dimsCount!=0)throw new Error(`Points size ('${e.length}') must be multiple of the dimensions count ('${this.dimsCount}').`);let t=[],i=e.length/this.dimsCount;for(let s=0;s<i;s++){let i=this.addPoint(e.slice(s*this.dimsCount,(s+1)*this.dimsCount));t.push(...i)}return this.#l+=i,t}addPoint(e){for(this.#o.push(...e);this.#o.length<this.windowSize*this.dimsCount;)this.#o.unshift(...this.#o.slice(0,this.dimsCount));for(;this.#o.length>this.windowSize*this.dimsCount;)this.#o=this.#o.slice(this.dimsCount);return this.filterBuffer()}filterBuffer(){let e=[];for(let t=0;t<this.windowSize;t++)for(let i=0;i<this.dimsCount;i++)isNaN(e[i])&&(e[i]=0),e[i]+=this.#o[t*this.dimsCount+i]*this.filter[t];return e}reset(){super.reset(),this.#l=0,this.#o.clear()}static resample(e,t){let i=new Float32Array(t),s=e.length/t,r=0;for(let n=0;n<t;n++){let a=(e.length-1)*n/(t-1),o=Math.floor(a),l=Math.ceil(a),h=a-o,u=s*(e[o]*(1-h)+e[l]*h);r+=u,i[n]=u}let n=1/r;for(let e=0;e<t;e++)i[e]*=n;return i}}class ue extends Z{#r;#n;constructor(e){super(),this.layout=e,this.pathPointProps={}}add(e,t){this.#r||(this.#r=ne.createInstance(this.layout,this.pathPointProps)),0==this.#r.points.length&&e.length>0&&e.unshift(...e.slice(0,this.layout.length)),t&&(e.length>=this.layout.length?e.push(...e.slice(e.length-this.layout.length,e.length)):e.push(...this.getLastPart()));let i=this.getFirstPart();return this.#r.points=i.concat(e),e}predict(e=[]){if(0==e.length)return e;this.#n?this.#n.points.clear():this.#n=ne.createInstance(this.layout,this.pathPointProps);let t=this.#n.points,i=this.getFirstPart();for(t.push(...i),t.push(...e),t.push(...t.slice(t.length-this.layout.length,t.length));t.length<4*this.layout.length;)t.unshift(t.slice(0,this.layout.length));return t}processImpl(e){let t=[];return e.length>0&&(t.push(...e.slice(0,this.layout.length)),t.push(...e),e.length>=this.layout.length&&t.push(...e.slice(e.length-this.layout.length,e.length))),e}getOutput(e,t){if(t==ue.OutputType.ADDITION){if(this.#r.points.length>=4*this.layout.length)return this.#r}else if(t==ue.OutputType.PREDICTION){if(this.#n.points.length>0)return this.#n}else if(e.length>0)return ne.createSharedInstance(this.layout,e,this.pathPointProps)}getFirstPart(){return this.#r.points.slice(Math.max(0,this.#r.points.length-3*this.layout.length),this.#r.points.length)}getLastPart(){return this.#r.points.slice(this.#r.points.length-this.layout.length,this.#r.points.length)}reset(){super.reset(),this.#r=null,this.#n=null}}class pe extends se{constructor(e=.1,t,i){super(t,i),this.spacing=e}split(e,t=8){let i=this.spacing;this.spacing=1,this.splitCount=t;let s=this.process(e);return this.spacing=i,delete this.splitCount,s}discretize(t,i){let s,r,n=this.path.points,a=this.splitCount,o=Math.max(1,10*(this.spacing>1?1:this.spacing)),l=0,h=t.segmentsCount-1,u=t.ts,p=t.tf;i&&(l=i.segmentIndexStart,h=i.segmentIndexEnd,u=i.ts,p=i.tf,this.state.segmentIndex=l-1);for(let i=l;i<h+1;i++){if(this.state.segmentIndex++,this.calculatePolynomials(t,i),isNaN(this.splitCount)){s||(s=w.createInstance(t.layout),r=w.createInstance(t.layout)),s.fill(i+1,t.points,t.layout,t.pointProps),r.fill(i+2,t.points,t.layout,t.pointProps);let n=e.distance(s.value,r.value),l=this.pathPointProps.size;this.state.layout.SIZE&&(l=Math.min(s.size,r.size)),a=Math.floor(o*(n/l)/this.spacing)+1}let l=1/a;for(let e=0;e<=a;e++){let t=!this.state.lastPointPosition,s=e/a;if(0==i&&s<u){if(!(s+l>=u))continue;s=u,t=this.spacing<=1}if(i==h&&s>=p){if(!(s<p+l))continue;s=p,t=this.lastSegment&&this.spacing<=1}if(i>0&&0==s)continue;let r=this.samplePoint(s);if(!t&&this.state.lastPointPosition){let e=new d(this.getPropValue(w.Property.X,r),this.getPropValue(w.Property.Y,r),this.getPropValue(w.Property.Z,r)),i=this.state.lastPointPosition.vec.squaredDistance(this.state.lastPointPosition.value,e.value),s=(this.state.layout.SIZE?(this.state.lastPointSize+r[this.state.layout.SIZE.index])/2:this.pathPointProps.size)*this.spacing;t=i>=s*s}t&&(n.push(...r),this.storeLastPoint(r),this.keepSegmentT(s))}}}}class ce extends Array{static get[Symbol.species](){return Array}constructor(...e){if(super(...e),e.some((e=>!(e instanceof W))))throw new Error("Expected data item type is Polygon");Object.defineProperty(this,"bounds",{get:()=>{let e;return this.length>0&&(this.forEach((t=>e=t.bounds.union(e))),e=e.ceil()),e},enumerable:!0}),Object.defineProperty(this,"vertices",{get:()=>this.triangulate(),enumerable:!0})}clone(){return new this.constructor(...this.map((e=>e.clone())))}push(...e){if(e.some((e=>!(e instanceof W))))throw new Error("Expected data item type is Polygon");super.push(...e)}triangulate(){return Float32Array.createSharedInstance().concat(...this.map((e=>e.vertices)))}transform(e){this.forEach((t=>t.transform(e)))}toJSON(){return{type:"PolygonArray",polygons:this.map((e=>e.toJSON()))}}static fromJSON(e){if("PolygonArray"!=e.type)throw new Error(`PolygonArray deserialization failed. JSON type is ${e.type}, expected PolygonArray.`);return new ce(...e.polygons.map((e=>W.fromJSON(e))))}static fromPathsData(e){return new ce(...e.map((e=>W.createInstance(e))))}}W.toPolygonArray=ce.fromPathsData;class de extends ce{constructor(...e){let t;super(...e),Object.defineProperty(this,"encoding",{get:()=>t,set:e=>{t=e,this.forEach((t=>t.encoding=e))},enumerable:!0})}union(e=!1,t=.1){let i=new G(this,this.bounds);i.subject=D.SimplifyPolygons(i.subject,k.pftNonZero),i.solution=D.CleanPolygons(i.subject,t*i.transform.scale),1==i.subject.length&&0==i.solution.first.length&&(i.solution=i.subject);let s=i.toPaths();return e?W.createSharedInstance(s.first,s.slice(1)):W.createInstance(s.first,s.slice(1))}intersects(e){e instanceof W&&(e=[e]);for(let t of this)for(let i of e)if(t.intersects(i))return{poly1:t,poly2:i};return null}toJSON(){let e=super.toJSON();return e.type="InkPath2D",e}static fromJSON(e){if("InkPath2D"!=e.type)throw new Error(`InkPath2D deserialization failed. JSON type is ${e.type}, expected InkPath2D.`);return new de(...e.polygons.map((e=>W.fromJSON(e))))}}class fe extends Z{static ARRAY_TYPE=de;#r;#n;#a;#i;constructor(e){super(),this.brush=e}processImpl(e,t){return t==fe.OutputType.ADDITION?(this.#r||(this.#r=new de),this.#i=this.#r):t==fe.OutputType.PREDICTION?(this.#n||(this.#n=new de),this.#i=this.#n):(this.#a||(this.#a=new de),this.#i=this.#a),this.#i.clear(),this.generatePolygons(e),this.#i}generatePolygons(e){if(!e)return this.#i;for(let t=0;t<e.length;t++){let i=e.getPointRef(t),s=this.applyBrush(i);this.#i.push(s)}}applyBrush(t){let i=this.createTransform(t),s=this.brush.selectShape(i.maxScale).shape,r=Float32Array.createSharedInstance(2*s.length);for(let t=0;t<s.length;t++){let n=t*s.stride,a=e.fromValues(s.getPointX(t),s.getPointY(t));e.transformMat2d(a,a,i),r[n]=a[0],r[n+1]=a[1]}return W.createSharedInstance(r)}createTransform(t){if(isNaN(t.size))throw new Error("Size information not found");let i=n.create(),s=t.size*t.scaleX,r=t.size*t.scaleY,a=Math.max(s,r);return n.translate(i,i,e.fromValues(t.x,t.y)),n.rotate(i,i,t.rotation),n.translate(i,i,e.fromValues(t.offsetX,t.offsetY)),n.scale(i,i,e.fromValues(s,r)),i.maxScale=a,i}reset(){super.reset(),this.#r&&this.#r.clear(),this.#n&&this.#n.clear(),this.#a&&(this.#a=new de)}}class me extends Z{static ARRAY_TYPE=de;#r;#n;#a;#i;#h;constructor(){super()}add(e,t){return this.#r||(this.#r=new de),this.#i=this.#r,this.#i.clear(),this.buildConvexHulls(e,!0),this.#i}processImpl(e,t){if(!(e instanceof de)){if(!(e instanceof W))throw new Error("ConvexHullChainProducer build 'input' type missmatch, expected type is oneof(Polygon, InkPath2D)");e=[e]}return t==me.OutputType.PREDICTION?(this.#n||(this.#n=new de),this.#i=this.#n):(this.#a||(this.#a=new de),this.#i=this.#a),this.#i.clear(),this.buildConvexHulls(e),this.#i}buildConvexHulls(e,t=!1){let i=this.#h;for(let t of e){if(i||1==e.length){let e=i?i.union(t):t.convex();this.#i.push(e)}i=t}t&&e.length>0&&(this.#h=e.last)}reset(){super.reset(),this.#h=null,this.#r&&this.#r.clear(),this.#n&&this.#n.clear(),this.#a&&this.#a.clear()}}let ge=!1;class ye{constructor(e,t,i=ye.WorkerType.CLASSIC){if(!ge)throw new Error("Constructor is private, use static method getInstance instead.");this.name=e,this.type=i,t&&t.startsWith("file://")&&(t=t.replace("file://","")),this.src=t,this.workers=[],this.transferables=[],this.status=ye.Status.CLOSED,this.resolver={};let s=0;Object.defineProperty(this,"nextID",{get:()=>String(s++),enumerable:!0,configurable:!0})}async open(e=this.src){if(this.status!=ye.Status.CLOSED)throw new Error(`${this.name} worker cannot be opened. Current status is ${this.status.name}.`);if(!e)throw new Error(`${this.name} worker location is not defined.`);let t,i;if("function"==typeof Worker)t=Worker,i=navigator.hardwareConcurrency||1;else{const e=await import("os"),s=await import("worker_threads"),{Worker:r}=s;t=r,i=e.cpus().length}this.ready=0;for(let s=0;s<i;s++){let i=this.name+s,r=new t(e,{type:this.type,name:i,workerData:{name:i}});r.name=s,r.on("message",(e=>"INIT"==e.action?this.confirmWorkerReady():this.recieve(e))),r.on("error",(e=>this.recieveError(e,s))),this.workers.push(r)}return this.status=ye.Status.OPEN_IN_PROGRESS,new Promise(((e,t)=>{this.workers.forEach(((e,t)=>e.postMessage({action:"INIT",worker:t}))),this.resolve=e}))}confirmWorkerReady(){this.ready++,this.ready==this.workers.length&&(this.resolve(),delete this.ready,delete this.resolve,this.status=ye.Status.OPEN)}close(){this.workers.forEach((e=>e.terminate())),this.workers.clear(),this.status=ye.Status.CLOSED}async broadcast(e,t){if(this.status!=ye.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);return new Promise(((i,s)=>{this.resolver[t]=i;for(let i of this.workers){let s=this.buildRequestMessage(e,t);if(!s)break;this.send(i.name,s)}}))}async broadcastMessage(e){if(this.status!=ye.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);if(!e.actionID)throw new Error("message actionID is required");return new Promise(((t,i)=>{this.resolver[e.actionID]=t;for(let t of this.workers)this.send(t.name,e)}))}send(e,t){if(this.status!=ye.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);if(!t)throw new Error("message is required");this.workers[e].postMessage(t,this.transferables),this.transferables.clear()}buildRequestMessage(e,t){throw new Error("ThreadBridge.buildRequestMessage(action, actionID) is abstract and should be implemented")}recieve(e){throw new Error("ThreadBridge.recieve(message) is abstract and should be implemented")}resolve(e,t){this.resolver[e](t),delete this.resolver[e]}recieveError(e,t){console.warn(`${this.name} worker ${t}: ${e.message}`),e.filename||console.error(e)}static getInstance(){return this.instance||(ge=!0,this.instance=new this,ge=!1),this.instance}}Object.defineEnum(ye,"Status",["OPEN","OPEN_IN_PROGRESS","CLOSED"]),ye.WorkerType={CLASSIC:"classic",MODULE:"module"};class Pe extends ye{static WORKER_NAME="ConvexHullProvider";constructor(){super(Pe.WORKER_NAME,Pe.buildWorkerURL(),Pe.buildWorkerURL().contains("/wacom-src/")?ye.WorkerType.MODULE:ye.WorkerType.CLASSIC),this.state={}}static buildWorkerURL(){if("function"==typeof DedicatedWorkerGlobalScope)return;let e="undefined"==typeof __location?import.meta.url:__location;return e=e.substring(0,e.lastIndexOf("/")),e.endsWith("workers")||(e+="/workers"),e+=`/${Pe.WORKER_NAME}.js`,e}async build(e,t,i){let s=this.nextID;return this.state[s]={type:t,input:e,output:new de,queue:[...e.slice()],lastPolygon:i,expected:e.length,processed:0},await this.broadcast("BUILD",s)}buildRequestMessage(e,t){let i={action:e,actionID:t},s=this.state[t];if("BUILD"!=e)throw new Error(`Unknow data action found: ${e}`);{let e=s.queue.shift();if(!e)return;let t,r=s.input.indexOf(e),n=0==r?s.lastPolygon:s.input[r-1];n?t=Array.of(...n.shape.points,...e.shape.points):(n=e,e=s.queue.shift(),e?(t=Array.of(...n.shape.points,...e.shape.points),s.updateIndex=!0,s.expected--,r++):t=n.shape.points),i.index=r,i.data=t}return i}recieve(e){let t=this.state[e.actionID],i=t.updateIndex?e.index-1:e.index;if(t.output[i]=W.createSharedInstance(e.data),t.processed++,t.processed==t.expected)delete this.state[e.actionID],this.keepAllData&&t.type==Z.OutputType.ADDITION&&(this.path||(this.path=new de),this.path.push(...t.output)),this.resolve(e.actionID,t.output);else{let t=this.buildRequestMessage(e.action,e.actionID);t&&this.send(e.worker,t)}}}class be extends Z{static ARRAY_TYPE=de;constructor(){super(),this.lastPolygon,this.convexHullProducer=Pe.getInstance(),Object.defineProperty(this,"closed",{get:()=>this.convexHullProducer.status==ye.Status.CLOSED,enumerable:!0})}static buildWorkerURL(){return Pe.buildWorkerURL()}async open(){await this.convexHullProducer.open()}close(){this.convexHullProducer.close()}async process(e,t=be.OutputType.PROCESSOR,i=!0){let s=this.lastPolygon;t==be.OutputType.ADDITION&&e.length>0&&(this.lastPolygon=e.last),i&&(this.lastPolygon=null);let r=await this.convexHullProducer.build(e,t,s);return this.getOutput(r)}reset(){super.reset(),this.lastPolygon=null}}class Ee extends Z{static ARRAY_TYPE=de;predict(e){return console.warn("Prediction merge is not recommended"),e}processImpl(e,t){return this.merge(e,t==Ee.OutputType.PROCESSOR)}merge(e,t){if(0!=e.length)return e.union(t)}}class Se extends Z{static ARRAY_TYPE=de;constructor(e=.1){super(),this.epsilon=e}predict(e){return console.warn("Prediction simplify is not recommended"),e}processImpl(e){return e instanceof W?e.simplifyRamerDouglasPeucker(this.epsilon):new e.constructor(...e.map((e=>e.simplify(this.epsilon))))}}function we(){}Object.defineEnum(we,"Stage",["PATH_PRODUCER","SMOOTHER","SPLINE_PRODUCER","SPLINE_INTERPOLATOR","BRUSH_APPLIER","CONVEX_HULL_CHAIN_PRODUCER","POLYGON_MERGER","POLYGON_SIMPLIFIER"]);const Ie=we.Stage,Oe=ae.Phase,ve=Z.OutputType;class xe{constructor(e){this.phase=e.phase;let t=isNaN(e.altitude)||isNaN(e.azimuth)?void 0:{altitude:e.altitude,azimuth:e.azimuth};Object.defineProperty(this,"x",{value:e.x,enumerable:!0}),Object.defineProperty(this,"y",{value:e.y,enumerable:!0}),Object.defineProperty(this,"z",{value:e.z,enumerable:!0}),Object.defineProperty(this,"timestamp",{value:e.timestamp,enumerable:!0,writable:!0}),Object.defineProperty(this,"force",{value:e.pressure,enumerable:!0}),Object.defineProperty(this,"pressure",{value:e.pressure,enumerable:!0}),Object.defineProperty(this,"rotation",{value:e.rotation,enumerable:!0}),Object.defineProperty(this,"radiusX",{value:e.radiusX,enumerable:!0}),Object.defineProperty(this,"radiusY",{value:e.radiusY,enumerable:!0}),Object.defineProperty(this,"altitude",{get:()=>(t||(t=this.computeTilt(e)||{}),t.altitude),enumerable:!0}),Object.defineProperty(this,"azimuth",{get:()=>(t||(t=this.computeTilt(e)||{}),t.azimuth),enumerable:!0}),e.pointer&&Object.defineProperty(this,"pointer",{value:e.pointer,enumerable:!0}),this.computedAzimuth=void 0}createPathPoint(e){return new w(this.x,this.y,this.z,e)}computeTilt(e){if(isNaN(e.tiltX)||isNaN(e.tiltY))return;let{tiltX:t,tiltY:i}=e,s=Math.tan(Math.toRadians(t)),r=Math.tan(Math.toRadians(i)),n=Math.sqrt(s*s+r*r);return{altitude:Math.atan2(1,n),azimuth:Math.atan2(r,s)}}speed(e,t){let i={x:0,y:0,time:0};return i=e&&!t?this.minus(e):t&&!e?t.minus(this):t.minus(e),i.time>0?xe.getMagnitude(i.x,i.y)/(i.time/1e3):(0==i.time||console.warn(`Speed out of range: ${i.time}ms`),0)}computeNearestAzimuthAngle(e){let t;if(isNaN(this.azimuth))return 0;if(e){if(isNaN(e.azimuth))return 0;let i=2*Math.PI,s=e.computedAzimuth||e.azimuth,r=parseInt(s/i);t=this.azimuth+r*i;let n=t-s;n>=Math.PI?t-=i:n<-Math.PI&&(t+=i)}else t=this.azimuth;return this.computedAzimuth=t,t}minus(e){return{x:this.x-e.x,y:this.y-e.y,time:this.timestamp-e.timestamp}}static getMagnitude(e,t){return Math.sqrt(e*e+t*t)}}Object.defineEnum(xe,"Property",["X","Y","Z","PHASE","TIMESTAMP","PRESSURE","RADIUS_X","RADIUS_Y","ALTITUDE","AZIMUTH","ROTATION"]);class Ae{constructor(e=[],t=[]){this.accumulatedAddition=e,this.lastPrediction=t,this.first=!1,this.last=!1}add(e,t,i=[]){e==ae.Phase.BEGIN?this.reset(!0):e==ae.Phase.END&&(this.last=!0),t&&this.accumulatedAddition.push(...t),this.lastPrediction=i}clone(){let e=new Ae(this.accumulatedAddition.slice(),this.lastPrediction.slice());return e.first=this.first,e.last=this.last,e}reset(e=!1){this.first=e,this.last=!1,this.accumulatedAddition.clear(),this.lastPrediction.clear()}}Object.defineProperty(globalThis,"DIGITAL_INK_ENV",{value:"AUTO",enumerable:!0,configurable:!0});let Re={version:"1.5.0"};Object.defineEnum(Re,"Type",["WEB","WORKER","NODE","SHELL"]),Object.defineEnum(Re,"Type2D",["SCREEN","OFFSCREEN"]),Object.defineEnum(Re,"TypeGL",["WEB","STACK"]),function(e){let t,i="BROWSER"!=DIGITAL_INK_ENV&&"object"==typeof process&&"function"==typeof require;t="object"==typeof window?"WEB":"function"==typeof importScripts?"WORKER":i?"NODE":"SHELL";let s="undefined"==typeof Screen?"OFFSCREEN":"SCREEN",r="undefined"==typeof WebGLRenderingContext?"STACK":"WEB";Object.defineProperty(Re,"commonJS",{value:i,enumerable:!0}),Object.defineProperty(Re,"type",{value:Re.Type[t],enumerable:!0}),Object.defineProperty(Re,"type2D",{value:Re.Type2D[s],enumerable:!0}),Object.defineProperty(Re,"typeGL",{value:Re.TypeGL[r],enumerable:!0})}();let Te={};if(Re.type==Re.Type.WEB)Te.Image=globalThis.Image,Te.ImageData=globalThis.ImageData,Te.CanvasRenderingContext2D=globalThis.CanvasRenderingContext2D,void 0===globalThis.OffscreenCanvas?(Te.OffscreenCanvas=function(e,t){let i=document.createElement("canvas");return i.width=e,i.height=t,i},Te.OffscreenCanvasRenderingContext2D=globalThis.CanvasRenderingContext2D):(Te.OffscreenCanvas=globalThis.OffscreenCanvas,Te.OffscreenCanvasRenderingContext2D=globalThis.OffscreenCanvasRenderingContext2D);else if(void 0!==globalThis.OffscreenCanvas)Te.Image=globalThis.Image,Te.ImageData=globalThis.ImageData,Te.OffscreenCanvas=globalThis.OffscreenCanvas,Te.OffscreenCanvasRenderingContext2D=globalThis.OffscreenCanvasRenderingContext2D;else if(Re.commonJS){const{Canvas:e,CanvasRenderingContext2D:t,Image:i,ImageData:s}=require("canvas");Te.Image=i,Te.ImageData=s,Te.OffscreenCanvas=e,Te.OffscreenCanvasRenderingContext2D=t}else console.warn(`Current env - ${Re.type.name}, do not provides OffscreenCanvas support`);function De(e){this.clearRect(0,0,this.canvas.width,this.canvas.height),e&&(this.fillStyle=e,this.fillRect(0,0,this.canvas.width,this.canvas.height))}Te.CanvasRenderingContext2D&&(Te.CanvasRenderingContext2D.prototype.clearCanvas=De),Te.OffscreenCanvasRenderingContext2D&&(Te.OffscreenCanvasRenderingContext2D.prototype.clearCanvas=De);const{Image:Ne,ImageData:Fe,OffscreenCanvas:Ce,CanvasRenderingContext2D:Me,OffscreenCanvasRenderingContext2D:ke}=Te;let Le;class Be{#u={};constructor(...e){if(Le)throw new Error("URIResolver instance already available");Le=this,Object.defineProperty(this,"items",{get:()=>Object.values(this.#u),enumerable:!0}),this.init(...e)}init(...e){throw new Error("URIResolver.init(...args) is abstract and should be implemented")}get(e){return this.#u[e]}register(e,t){this.#u[e]=t}resolve(e){let t;if(e.includes("?")){let i=e.split("?")[0],s=this.#u[i];if(s){let i=e.split("?")[1],r=[];i.split("&").forEach((e=>{let t=e.split("=")[1],i=parseFloat(t);isFinite(i)?t=i:"true"==t?t=!0:"false"==t&&(t=!1),r.push(t)})),t=function(){return s(...Array.from(arguments).concat(r))}}}else t=this.#u[e];if(!t)throw new Error(`Failed to resolve ${e}`);return t}}Object.defineProperty(Be,"instance",{get:()=>Le});class _e{static repetitionsCache=new Set;constructor(e,t){this.name=e,!e||_.isValidURL(e)||_e.repetitionsCache.has(e)||(_e.repetitionsCache.add(e),console.warn(`The string ${e} is not a well formed URI`)),Object.defineProperty(this,"value",{get:function(){if(!t){if(!this.name)throw new Error("Resource descriptor identifier not found. Cannot resolve resource content.");if("function"==typeof this.resolve&&(t=this.resolve(this.name)),!t){if(!Be.instance)throw new Error(`Resource URI ${this.name} cannot be resolved. URIResolver not implemented yet. Please implement and instantiate.`);t=Be.instance.resolve(this.name)}if(!t)throw new Error(`Resource URI ${this.name} cannot be resolved. Please provide resource definition in URIResolver init implementation.`)}return t},set:function(e){t=e},enumerable:!0})}toJSON(){let e=this.value;return ArrayBuffer.isTypedArray(e)?e=$.encode(e,this.encoding):"function"==typeof e&&(e=e()),{name:this.name,value:e}}static fromJSON(e){let t=e.value;return $.isTypedArrayData(t)&&(t=$.decode(t)),new _e(e.name,t)}static getInstance(e,t){return new _e(t,e)}}class je{constructor(e){_.isValidURL(e)||(_e.repetitionsCache.has(e)||(_e.repetitionsCache.add(e),console.warn(`Brush URI ${e} is not a well formed URI`)),e=this.constructor.onInvalidName(e)),Object.defineProperty(this,"id",{value:e}),Object.defineProperty(this,"uri",{value:e}),Object.defineProperty(this,"name",{value:e,enumerable:!0})}toJSON(){throw new Error("Brush.toJSON() should be implemented")}static fromJSON(e){throw new Error("static Brush.fromJSON() should be implemented")}static onInvalidName(e){return e}}class $e{static defaults={CIRCLE_PRECISION:20,CIRCLE_RADIUS:.5,ELLIPSE_PRECISION:20,ELLIPSE_RADIUS_X:.5,ELLIPSE_RADIUS_Y:.25,STAR_POINTS:5,STAR_RADIUS:.5,STAR_INTERNAL_RADIUS:.25};static createCircle(e=$e.defaults.CIRCLE_PRECISION,t=$e.defaults.CIRCLE_RADIUS,i={x:0,y:0}){return $e.createEllipse(e,t,t,i)}static createEllipse(e=$e.defaults.ELLIPSE_PRECISION,t=$e.defaults.ELLIPSE_RADIUS_X,i=$e.defaults.ELLIPSE_RADIUS_Y,s={x:0,y:0}){let r=[],n=2*Math.PI/e;if(t<=0)throw new Error(`Invalid radius x found ${t} > 0`);if(i<=0)throw new Error(`Invalid radius y found ${i} > 0`);for(let a=0;a<e;a++){let e=a*n,o=t*Math.cos(e),l=i*Math.sin(e);r.push(s.x+o,s.y+l)}return Float32Array.createSharedInstance(r)}static createStar(e=$e.defaults.STAR_POINTS,t=$e.defaults.STAR_INTERNAL_RADIUS,i=$e.defaults.STAR_RADIUS){let s=[];if(i<=0)throw new Error(`Invalid radius found ${i} > 0`);if(t<=0)throw new Error(`Invalid internal radius found ${t} > 0`);if(t>i)throw new Error(`Invalid internal radius found 0 < ${t} < ${i}`);let r=2*Math.PI/e;for(let n=0;n<e;n++){let e=n*r,a=i*Math.cos(e),o=i*Math.sin(e),l=t*Math.cos(e+r/2),h=t*Math.sin(e+r/2);s.push(a,o,l,h)}return Float32Array.createSharedInstance(s)}}class Ue{static SHAPE_FRAME=new V(-.5,-.5,1,1);constructor(e,t=1){this.size=t,Object.defineProperty(this,"descriptor",{value:{shape:void 0},enumerable:!0}),Object.defineProperty(this,"shape",{get:function(){if(!e){if("function"==typeof(e=this.descriptor.shape.value)&&(e=e()),(Array.isArray(e)||e instanceof Float32Array)&&(e=W.createSharedInstance(e)),!(e instanceof W))throw new Error("Expected shape type is Polygon");Ue.fitShape(e)}return e},set:function(t){if(!t)throw new Error("BrushPrototype: shape not found");"string"==typeof t?t=new _e(t):t instanceof W||t instanceof Float32Array||Array.isArray(t)?t=_e.getInstance(t):t instanceof _e||(t=new _e(t.name,t.value)),e=null,this.descriptor.shape=t,this.descriptor.shape.resolve=Ue.resolve},enumerable:!0}),this.shape=e}toJSON(){return this.shape.encoding=this.encoding,{shape:{name:this.descriptor.shape.name,value:this.shape.toJSON()},size:this.size}}static fromJSON(e){return new Ue({name:e.shape.name,value:W.fromJSON(e.shape.value)},e.size)}static create(e,t=0,...i){let s,r=e;switch(e){case Ue.Type.CIRCLE:s=$e.createCircle(...i),r+=`?precision=${i[0]||$e.defaults.CIRCLE_PRECISION}&radius=${i[1]||$e.defaults.CIRCLE_RADIUS}`;break;case Ue.Type.ELLIPSE:s=$e.createEllipse(...i),r+=`?precision=${i[0]||$e.defaults.ELLIPSE_PRECISION}&radiusX=${i[1]||$e.defaults.ELLIPSE_RADIUS_X}&radiusY=${i[2]||$e.defaults.ELLIPSE_RADIUS_Y}`;break;case Ue.Type.STAR:s=$e.createStar(...i),r+=`?points=${i[0]||$e.defaults.STAR_POINTS}&internalRadius=${i[1]||$e.defaults.STAR_INTERNAL_RADIUS}&radius=${i[2]||$e.defaults.STAR_RADIUS}`;break;default:console.error(`Brush2D: createShape fails with ${e} type`)}return new Ue({name:r,shape:s},t)}static resolve(e){let t,i=e.split("?"),s=i.first;if(Object.values(Ue.Type).includes(s)){let e=i.last.split("&"),r={};switch(e.forEach((e=>{r[e.substring(0,e.indexOf("="))]=e.substring(e.indexOf("=")+1)})),s){case Ue.Type.CIRCLE:{let e=r.precision?parseInt(r.precision):void 0,i=r.radius?parseFloat(r.radius):1;t=$e.createCircle(e,i);break}case Ue.Type.ELLIPSE:{let e=r.precision?parseInt(r.precision):void 0,i=r.radiusX?parseFloat(r.radiusX):void 0,s=r.radiusY?parseFloat(r.radiusY):void 0;t=$e.createEllipse(e,i,s);break}case Ue.Type.STAR:{let e=r.points?parseInt(r.points):void 0,i=r.radius?parseFloat(r.radius):void 0,s=r.internalRadius?parseFloat(r.internalRadius):void 0;t=$e.createStar(e,s,i);break}default:console.error(`Brush2D: createShape fails with ${s} type`)}}return t}static fitShape(e){if(!(e instanceof W))throw new Error("Expected shape type is Polygon");e.center(),e.fit(Ue.SHAPE_FRAME)}}async function Ye(e,t="binary",i={}){if(e instanceof Uint8Array)return e;let s,r=await fetch(e,Object.assign({mode:"no-cors"},i));if("json"==t)s=await r.json();else if("text"==t)s=await r.text();else if("binary"==t){let e=await r.arrayBuffer();s=new Uint8Array(e)}else{let e=await r.blob();s="base64"==t?await function(e){return new Promise(((t,i)=>{let s=new FileReader;s.onloadend=()=>t("data:"==s.result?"":s.result),s.onerror=i,s.readAsDataURL(e)}))}(e):e}return s}async function Ge(e,t="binary",i={}){return Ye(e,t,i)}async function Xe(e){let t;return t="string"==typeof e||"undefined"==typeof createImageBitmap?await function(e){return new Promise(((t,i)=>{let s,r=new Ne;r.crossOrigin="anonymous",r.onload=()=>{if(Re.type2D==Re.Type2D.OFFSCREEN){const e=new Ce(r.width,r.height);e.getContext("2d").drawImage(r,0,0),t(e)}else s&&URL.revokeObjectURL(s),t(r)},r.onerror=i,"string"==typeof e?r.src=e:Re.type2D==Re.Type2D.OFFSCREEN?e instanceof Uint8Array?r.src=Buffer.from(e):e instanceof Ce?t(e):r.src=e:(e instanceof Uint8Array&&(e.byteLength!=e.buffer.byteLength&&(e=e.slice()),e=e.buffer),e instanceof ArrayBuffer&&(e=new Blob([e],{type:"image/png"})),s=URL.createObjectURL(e),r.src=s)}))}(e):e instanceof ArrayBuffer||e instanceof Uint8Array?await createImageBitmap(new Blob([e],{type:"image/png"})):await createImageBitmap(e),t}Ue.Type={ELLIPSE:"will://brush/3.0/shape/Ellipse",CIRCLE:"will://brush/3.0/shape/Circle",STAR:"will://brush/3.0/shape/Star"};class ze extends je{constructor(e,t,i,s=1){super(e),isFinite(i)&&(s=i,i=void 0),s<=0&&(console.warn(`Invalid spacing found ${s}. It should be positive number.`),s=1),Object.defineProperty(this,"shape",{get:()=>t,set:e=>{if(e instanceof Float32Array&&(e=new Ue(e)),e instanceof Ue&&(e=[e]),e.some((e=>!(e instanceof Ue))))throw console.warn(e),new Error("Brush2D: Invalid shape found");e.sort(_.comparator({sortBy:"size",sortOrder:"asc"})),t=e},enumerable:!0}),this.shape=t,this.fill=i,this.spacing=s}async configure(e){if(this.pattern||!this.fill)return;if(!(e instanceof Me||e instanceof ke))throw new Error("ctx is not instance of CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D");let t=await Xe(this.fill);this.pattern=e.createPattern(t,"repeat")}selectShape(e){let t;for(let i=1;i<this.shape.length;i++)if(this.shape[i].size>e){t=this.shape[i-1];break}return t||(t=this.shape.last),t.shape}toJSON(){return{type:"Brush2D",name:this.name,spacing:this.spacing,shape:this.shape.map((e=>(e.encoding=this.encoding,e.toJSON())))}}static fromJSON(e){let t=1==e.shape.length?Ue.fromJSON(e.shape[0]):e.shape.map((e=>Ue.fromJSON(e)));return new ze(e.name,t,e.spacing)}}function He(){}He.BlendMode={SOURCE_OVER:"source-over",DESTINATION_OVER:"destination-over",DESTINATION_IN:"destination-in",DESTINATION_OUT:"destination-out",LIGHTER:"lighter",COPY:"copy",MIN:"MIN",MAX:"MAX",DIRECT_SOURCE_OUT:"DIRECT_SOURCE_OUT",DIRECT_DESTINATION_OUT:"DIRECT_DESTINATION_OUT"};const qe=He.BlendMode;class Je{constructor(e,t){Object.defineProperty(this,"ctx",{value:e,enumerable:!0}),Object.defineProperty(this,"value",{value:t,enumerable:!0}),Object.defineProperty(this,"texture",{value:t,enumerable:!0})}async update(e,t){if(Array.isArray(e)){let i=[],s=e;for(let e of s){let t=await Xe(e);i.push(t)}this.completeMipMap(i),this.fill(i,t)}else{let t=e,i=await Xe(t);this.fill(i)}}completeMipMap(e){if(e.sort(((e,t)=>t.width-e.width)),1==e.last.width)return;let t=e.last.width;for(;t>1;){t/=2;let i=new Ce(e.last.width/2,e.last.height/2);i.getContext("2d").drawImage(e.last,0,0,i.width,i.height),e.push(i)}}fill(e,t){let i=this.ctx,s=this.value;if(i.bindTexture(i.TEXTURE_2D,s),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),Array.isArray(e)){let s=e;this.size=[],s.forEach(((e,t)=>{i.texImage2D(i.TEXTURE_2D,t,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e),this.size.push({width:e.width,height:e.height}),e.close&&e.close()})),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR_MIPMAP_NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR)}else i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e),this.size={width:e.width,height:e.height},e.close&&e.close();i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),i.bindTexture(i.TEXTURE_2D,null),this.logError(this.ctx,s.name)}readPixels(){let e=this.ctx,t=this.value,i=(i,s)=>{let r=new Uint8Array(i.width*i.height*4);return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,s),e.readPixels(0,0,i.width,i.height,e.RGBA,e.UNSIGNED_BYTE,r),r},s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s);let r=Array.isArray(this.size)?this.size.map(i):i(this.size,0);return e.deleteFramebuffer(s),r}logError(){let e=this.ctx.getError();if(e>0){let t=Object.keys(this.ctx.constructor.prototype).filter((t=>this.ctx[t]===e)).join(" | ");console.error(`WebGL error - ${this.texture.name}: ${e} - ${t}`)}}static createInstance(e,t=e.CLAMP_TO_EDGE,i=e.NEAREST){let s=e.createTexture();return e.bindTexture(e.TEXTURE_2D,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,i),e.bindTexture(e.TEXTURE_2D,null),new Je(e,s)}}class Ve extends je{constructor(e,t,i,s={},r={}){super(e),this.spacing=s.spacing||.15,this.scattering=s.scattering||0,this.rotationMode=s.rotationMode||Ve.RotationMode.RANDOM;let n,a=s.blendMode||qe.SOURCE_OVER;Object.defineProperty(this,"blendMode",{get:()=>a,set:e=>{if(!e)throw new Error("BrushGL blendMode is required");a=e}}),Object.defineProperty(this,"particleSettings",{get:()=>({spacing:this.spacing,scattering:this.scattering,blendMode:this.blendMode,rotationMode:this.rotationMode}),enumerable:!0}),Object.defineProperty(this,"fillTextureSettings",{get:()=>({randomize:this.randomizeFill,size:this.fillTextureSize,offset:this.fillTextureOffset}),enumerable:!0}),Object.defineProperty(this,"descriptor",{value:{shape:void 0,fill:void 0},enumerable:!0}),Object.defineProperty(this,"shape",{get:()=>Array.isArray(this.descriptor.shape)?this.descriptor.shape.map((e=>e.value)):this.descriptor.shape.value,enumerable:!0}),Object.defineProperty(this,"fill",{get:()=>this.descriptor.fill.value,enumerable:!0}),Object.defineProperty(this,"encoding",{get:()=>n,set:e=>{n=e,Array.isArray(this.descriptor.shape)?this.descriptor.shape.forEach((t=>t.encoding=e)):this.descriptor.shape.encoding=e,this.descriptor.fill.encoding=e},enumerable:!0}),this.updateShape(t),this.updateFill(i,r)}async updateShape(e){Array.isArray(e)?e=e.map((e=>"string"==typeof e?_e.getInstance(e):e instanceof _e?e:new _e(e.name,e.value))):"string"==typeof e?e=_e.getInstance(e):e instanceof _e||(e=new _e(e.name,e.value)),this.descriptor.shape=e,this.ctx&&await this.configureShape()}async updateFill(e,t={}){if(this.randomizeFill=!("randomize"in t)||t.randomize,this.fillTextureSize=t.size,this.fillTextureOffset=t.offset||{x:0,y:0},Array.isArray(e))throw new Error("Mipmap is not compatible whith fill texture");"string"==typeof e?e=_e.getInstance(e):e instanceof _e||(e=new _e(e.name,e.value)),this.descriptor.fill=e,this.ctx&&await this.configureFill()}async configure(e){this.ctx=e,await this.configureShape(),await this.configureFill()}async configureShape(){this.shapeTexture||(this.shapeTexture=Je.createInstance(this.ctx,this.ctx.CLAMP_TO_EDGE,this.ctx.LINEAR)),await this.shapeTexture.update(this.shape,this.spacing<=1)}async configureFill(){this.fillTexture||(this.fillTexture=Je.createInstance(this.ctx,this.ctx.REPEAT,this.ctx.NEAREST)),await this.fillTexture.update(this.fill),this.fillTextureSize||(this.fillTextureSize=this.fillTexture.size)}async getShapeBinary(){let e;if(Array.isArray(this.shape)){let t=[];for(let e of this.shape){let i=await Ge(e);t.push(i)}e=t}else e=await Ge(this.shape);return e}async getFillBinary(){return await Ge(this.fill)}toJSON(){return{type:"BrushGL",name:this.name,shape:Array.isArray(this.descriptor.shape)?this.descriptor.shape.map((e=>e.toJSON())):this.descriptor.shape.toJSON(),fill:this.descriptor.fill.toJSON(),particleSettings:{spacing:this.spacing,scattering:this.scattering,blendMode:this.blendMode.name,rotationMode:this.rotationMode.name},fillTextureSettings:{randomize:this.randomizeFill,size:this.fillTextureSize,offset:this.fillTextureOffset}}}static fromJSON(e){e.particleSettings.blendMode=qe[e.particleSettings.blendMode],e.particleSettings.rotationMode=Ve.RotationMode[e.particleSettings.rotationMode];let t=Array.isArray(e.shape)?e.shape.map((e=>_e.fromJSON(e))):_e.fromJSON(e.shape),i=_e.fromJSON(e.fill);return new Ve(e.name,t,i,e.particleSettings,e.fillTextureSettings)}equals(e){return e==this&&e.shapeTexture==this.shapeTexture&&e.fillTexture==this.fillTexture}delete(){this.deleteShape(),this.deleteFill(),delete this.ctx}deleteShape(){this.shapeTexture&&(this.ctx.deleteTexture(this.shapeTexture.texture),delete this.shapeTexture)}deleteFill(){this.fillTexture&&(this.ctx.deleteTexture(this.fillTexture.texture),delete this.fillTexture)}}Object.defineEnum(Ve,"RotationMode",["NONE","RANDOM","TRAJECTORY"]);const We=[Ie.SMOOTHER,Ie.POLYGON_MERGER,Ie.POLYGON_SIMPLIFIER],Ze=[Ie.SPLINE_PRODUCER,Ie.SPLINE_INTERPOLATOR,Ie.BRUSH_APPLIER,Ie.CONVEX_HULL_CHAIN_PRODUCER,Ie.POLYGON_MERGER,Ie.POLYGON_SIMPLIFIER];class Ke{#p;constructor(){this.layout=[w.Property.X,w.Property.Y],this.pathSegment=new Ae,this.pathProducer=new oe(this.layout),this.smoother=new he(this.layout.length),this.splineProducer=new ue(this.layout),this.distanceInterpolator=new pe,this.curvatureInterpolator=new re,this.brushApplier=new fe,this.polygonMerger=new Ee,this.polygonSimplifier=new Se,this.splineProducer.keepAllData=!0,this.phase=void 0,this.pointerID=void 0,this.concatSegments=!1,this.lastPipelineStage=void 0,this.excludedPipelineStages=[],this.configured=!1,Object.defineProperty(this,"allData",{get:()=>{let e={};return this.lastPipelineStage&&(this.smoother.keepAllData&&(e.smootherPoints=this.smoother.allData),this.splineInterpolator.keepAllData&&this.lastPipelineStage.value>Ie.SPLINE_INTERPOLATOR.value&&(e.interpolatedSpline=this.splineInterpolator.allData),this.brushApplier.keepAllData&&this.lastPipelineStage.value>Ie.BRUSH_APPLIER.value&&(e.shapesPath=this.brushApplier.allData),this.convexHullChainProducer.keepAllData&&this.lastPipelineStage.value>Ie.CONVEX_HULL_CHAIN_PRODUCER.value&&(e.convexPath=this.convexHullChainProducer.allData)),e}}),Object.defineProperty(this,"prediction",{get:()=>this.pathProducer.prediction,set:e=>this.pathProducer.prediction=e,enumerable:!0})}configure(e={}){if(this.reset(this.pointerID),e.onBuildComplete)throw new Error("[InkBuilderSettings] onBuildComplete property is deprecated. Use InkBuilder instance onComplete property to set callback.");if("mergePrediction"in e&&console.warn("[InkBuilderSettings] 'mergePrediction' property is deprecated. Do not affects PolygonMerger behaviour."),!e.brush)throw new Error("[InkBuilderSettings] brush property is required");if(e.excludedPipelineStages){if(!Array.isArray(e.excludedPipelineStages))throw new Error("Expected type of excludedPipelineStages is Array instance");let t=e.excludedPipelineStages.filter((e=>!We.includes(e)));t.length>0&&console.warn(`[InkBuilderSettings] excludedPipelineStages property includes steps which cannot be excluded: ${t.map((e=>e.name)).join(", ")}`),this.excludedPipelineStages=e.excludedPipelineStages.slice()}if(!this.excludedPipelineStages.includes(Ie.SMOOTHER)&&e.movingAverageWindowSize&&(this.smoother.movingAverageWindowSize=e.movingAverageWindowSize),e.lastPipelineStage){if(!Ze.includes(e.lastPipelineStage))throw new Error(`[InkBuilderSettings] lastPipelineStage property expects one of: ${Ze.map((e=>e.name)).join(", ")}`);if(this.excludedPipelineStages.includes(e.lastPipelineStage))throw new Error(`[InkBuilderSettings] lastPipelineStage ${e.lastPipelineStage.name} is disabled, check excludedPipelineStages configuration`);if(e.brush instanceof Ve&&e.lastPipelineStage!=Ie.SPLINE_INTERPOLATOR)throw new Error(`[InkBuilderSettings] lastPipelineStage ${e.lastPipelineStage.name} is not compatible with provided brush`);this.lastPipelineStage=e.lastPipelineStage}switch(this.brush=e.brush,this.brush instanceof ze&&(this.brushApplier.brush=this.brush),this.lastPipelineStage||(this.brush instanceof ze?(this.brush.spacing>1?this.lastPipelineStage=Ie.BRUSH_APPLIER:this.excludedPipelineStages.includes(Ie.POLYGON_SIMPLIFIER)&&this.excludedPipelineStages.includes(Ie.POLYGON_MERGER)?this.lastPipelineStage=Ie.CONVEX_HULL_CHAIN_PRODUCER:this.lastPipelineStage=Ie.POLYGON_MERGER,this.lastPipelineStage==Ie.POLYGON_MERGER&&(this.concatSegments=Boolean(e.concatSegments))):this.lastPipelineStage=Ie.SPLINE_INTERPOLATOR),this.lastPipelineStage==Ie.SPLINE_INTERPOLATOR||this.lastPipelineStage==Ie.BRUSH_APPLIER?(this.splineInterpolator=this.distanceInterpolator,this.splineInterpolator.spacing=this.brush.spacing,this.splineInterpolator.scattering=this.brush.scattering,this.splineInterpolator.calculateDerivates=this.brush instanceof Ve):(this.splineInterpolator=this.curvatureInterpolator,this.splineInterpolator.errorThreshold=e.errorThreshold||.15),this.splineInterpolator.keepSplineParameters=!!e.keepSplineParameters,this.splineInterpolator.keepAllData=!1,this.brushApplier.keepAllData=!1,this.convexHullChainProducer.keepAllData=!1,this.polygonMerger.keepAllData=!1,this.polygonSimplifier.keepAllData=!1,this.lastPipelineStage){case Ie.SPLINE_PRODUCER:break;case Ie.SPLINE_INTERPOLATOR:this.splineInterpolator.keepAllData=!0;break;case Ie.BRUSH_APPLIER:this.brushApplier.keepAllData=!0;break;case Ie.CONVEX_HULL_CHAIN_PRODUCER:this.convexHullChainProducer.keepAllData=!0;break;case Ie.POLYGON_MERGER:this.polygonMerger.keepAllData=!0;break;case Ie.POLYGON_SIMPLIFIER:this.polygonSimplifier.keepAllData=!0;break;default:throw console.warn(this.lastPipelineStage),new Error("[InkBuilderSettings] Invalid lastPipelineStage found")}if(this.lastPipelineStage==Ie.POLYGON_SIMPLIFIER&&(console.warn("[InkBuilderSettings] Pipeline stage POLYGON_SIMPLIFIER is deprecated. POLYGON_MERGER stage is recommended as last stage."),this.polygonSimplifier.epsilon=e.epsilon||.1),e.keepAllData){e.keepAllData.includes(this.lastPipelineStage)&&(console.warn(`[InkBuilderSettings] keepAllData contains last pipeline stage ${this.lastPipelineStage}. Duplicate is dropped.`),e.keepAllData.remove(this.lastPipelineStage)),e.keepAllData.includes(Ie.PATH_PRODUCER)&&(console.warn(`[InkBuilderSettings] keepAllData contains stage ${Ie.PATH_PRODUCER}, sensor input is accessible through InputDevice output - SensorData. Dropped from keepAllData.`),e.keepAllData.remove(Ie.PATH_PRODUCER)),e.keepAllData.includes(Ie.SPLINE_PRODUCER)&&(console.warn(`[InkBuilderSettings] keepAllData contains stage ${Ie.SPLINE_PRODUCER}. Use getSpline() method to acceess spline data. Dropped from keepAllData.`),e.keepAllData.remove(Ie.SPLINE_PRODUCER));for(let t of e.keepAllData){if(this.excludedPipelineStages.includes(t))throw new Error(`[InkBuilderSettings] keepAllData contains stage ${t}, configured as stage in excludedPipelineStages.`);switch(t){case Ie.SMOOTHER:this.smoother.keepAllData=!0;break;case Ie.SPLINE_INTERPOLATOR:this.splineInterpolator.keepAllData=!0;break;case Ie.BRUSH_APPLIER:this.brushApplier.keepAllData=!0;break;case Ie.CONVEX_HULL_CHAIN_PRODUCER:this.convexHullChainProducer.keepAllData=!0;break;default:throw console.warn(t),new Error("Invalid stage found")}}this.#p=e.keepAllData}else this.#p=[];if(e.pathPointCalculator&&(this.calculator=e.pathPointCalculator,this.pathProducer.pathPointCalculator=e.pathPointCalculator),!e.layout)throw new Error("[InkBuilderSettings] layout property is required");{let t=e.pathPointProps||{};if(this.layout=e.layout,this.brush instanceof ze){if(this.layout.includes(w.Property.RED))throw new Error("RED layout channel is not supported for non particles strokes");if(this.layout.includes(w.Property.GREEN))throw new Error("GREEN layout channel is not supported for non particles strokes");if(this.layout.includes(w.Property.BLUE))throw new Error("BLUE layout channel is not supported for non particles strokes");if(this.layout.includes(w.Property.ALPHA))throw new Error("ALPHA layout channel is not supported for non particles strokes")}if(!this.layout.includes(w.Property.RED)&&isNaN(t.red))throw new Error("Stroke color red channel information is required. Please provide via layout or through configure settings via pathPointProps property.");if(!this.layout.includes(w.Property.GREEN)&&isNaN(t.green))throw new Error("Stroke color green channel information is required. Please provide via layout or through configure settings via pathPointProps property.");if(!this.layout.includes(w.Property.BLUE)&&isNaN(t.blue))throw new Error("Stroke color blue channel information is required. Please provide via layout or through configure settings via pathPointProps property.");if(!this.layout.includes(w.Property.ALPHA)&&isNaN(t.alpha))throw new Error("Stroke color alpha channel information is required. Please provide via layout or through configure settings via pathPointProps property.");this.pathProducer.layout=this.layout,this.smoother.dimsCount=this.layout.length,this.splineProducer.layout=this.layout,this.splineProducer.pathPointProps=t}this.configured=!0}add(e,t){if(!this.configured)throw new Error("InkBuilder instance is not configured yet, use configure method to configure the instance.");if(!this.calculator)throw new Error("InkBuilder instance is not configured properly, pathPointCalculator property is required");if(!e.phase)throw new Error("SensorPoint phase is not found");this.phase=e.phase;let i,s=new xe(e);t&&(this.prediction?i=new xe(t):console.warn("Prediction sensor point is available, but ignored, prediction is disabled")),this.device&&(this.phase==oe.Phase.BEGIN&&this.device.openStream(e),this.device.add(s),this.phase==oe.Phase.END&&(this.sensorData=this.device.closeStream()));let r=this.pathProducer.add(this.phase,s,i);this.pathSegment.add(this.phase,r.added,r.predicted)}ignore(e){if(!e.phase)throw new Error("SensorPoint phase is not found");this.device&&e&&e.phase==oe.Phase.UPDATE&&this.device.add(new xe(e),!0)}build(){throw new Error("InkBuilderAbstract.build() is abstract and should be implemented")}processSegment(e,t,i){throw new Error("InkBuilderAbstract.processSegment(path, type, lastSegment) is abstract and should be implemented")}getSensorData(){return this.sensorData}getSpline(){return this.splineProducer.allData}getAllData(){if(0==this.#p.length)return;let e={};for(let t of this.#p)switch(t){case Ie.SMOOTHER:e.smoother=this.smoother.allData;break;case Ie.SPLINE_INTERPOLATOR:e.interpolatedSpline=this.splineInterpolator.allData;break;case Ie.BRUSH_APPLIER:e.shapesPath=this.brushApplier.allData;break;case Ie.CONVEX_HULL_CHAIN_PRODUCER:e.convexPath=this.convexHullChainProducer.allData;break;default:throw console.warn(t),new Error("Invalid stage found")}return e}getInkPath(){let e;switch(this.lastPipelineStage){case Ie.SPLINE_PRODUCER:return void console.warn("Pipeline stage SPLINE_PRODUCER is configured as lastPipelineStage. Ink Path is a result from Spline processing.");case Ie.SPLINE_INTERPOLATOR:e=this.splineInterpolator.allData;break;case Ie.BRUSH_APPLIER:e=this.brushApplier.allData;break;case Ie.CONVEX_HULL_CHAIN_PRODUCER:e=this.convexHullChainProducer.allData;break;case Ie.POLYGON_MERGER:e=this.polygonMerger.allData;break;case Ie.POLYGON_SIMPLIFIER:e=this.polygonSimplifier.allData;break;default:throw console.warn(this.lastPipelineStage),new Error("Invalid lastPipelineStage found")}if(this.concatSegments){let t;this.lastPipelineStage!=Ie.POLYGON_MERGER&&this.lastPipelineStage!=Ie.POLYGON_SIMPLIFIER||(t=this.polygonMerger.process(e)),this.lastPipelineStage==Ie.POLYGON_SIMPLIFIER&&(t=this.polygonSimplifier.process(t)),t&&(e=new de(t))}return e}abort(){this.device&&this.device.closeStream(!0),this.reset()}reset(e){this.pointerID=e,this.phase=void 0,this.concatSegments=!1,this.lastPipelineStage=void 0,this.excludedPipelineStages.clear(),this.sensorData=void 0,this.pathProducer.reset(),this.smoother.reset(),this.splineProducer.reset(),this.distanceInterpolator.reset(),this.curvatureInterpolator.reset(),this.brushApplier.reset(),this.convexHullChainProducer.reset(),this.polygonMerger.reset(),this.polygonSimplifier.reset(),this.configured=!1}}Ke.Phase=oe.Phase;class Qe extends Ke{constructor(){super(),this.convexHullChainProducer=new me}build(){let e=this.buildSegment();return e.phase=this.phase,e.pointerID=this.pointerID,this.onComplete&&this.onComplete(e),this.phase==Oe.END&&(delete this.phase,delete this.pipeline),e}buildSegment(){let e={};return this.pathSegment.accumulatedAddition.length>0&&(e.added=this.processSegment(this.pathSegment.accumulatedAddition,ve.ADDITION,this.pathSegment.last),e.pipeline=this.pipeline,e.added&&(e.added.segment=!0)),this.prediction&&this.pathSegment.lastPrediction.length>0&&(e.predicted=this.processSegment(this.pathSegment.lastPrediction,ve.PREDICTION,this.pathSegment.last),e.predicted&&(e.predicted.segment=!0)),this.pathSegment.reset(),e}processSegment(e,t,i){if(this.excludedPipelineStages.includes(Ie.SMOOTHER)||(e=this.smoother.process(e,t,i)),e=this.splineProducer.process(e,t,i))return this.lastPipelineStage==Ie.SPLINE_PRODUCER?e:this.processSpline(e,t,i)}processSpline(e,t=ve.PROCESSOR,i=!0){t==ve.ADDITION&&(this.pipeline={}),t==ve.ADDITION&&(this.pipeline.spline=e);let s,r=this.splineInterpolator.process(e,t,i);if(this.lastPipelineStage==Ie.SPLINE_INTERPOLATOR)return r;if(r)return t==ve.ADDITION&&(this.pipeline.interpolatedSpline=r),r=this.brushApplier.process(r,t,i),this.lastPipelineStage==Ie.BRUSH_APPLIER?r:(t==ve.ADDITION&&(this.pipeline.shapesPath=r),r=this.convexHullChainProducer.process(r,t,i),this.lastPipelineStage==Ie.CONVEX_HULL_CHAIN_PRODUCER?r:(t==ve.ADDITION&&(this.pipeline.convexPath=r),t==ve.PREDICTION?r:this.excludedPipelineStages.includes(Ie.POLYGON_MERGER)||(s=this.polygonMerger.process(r,t,i),this.lastPipelineStage!=Ie.POLYGON_MERGER)?(this.excludedPipelineStages.includes(Ie.POLYGON_SIMPLIFIER)||(s=this.polygonSimplifier.process(s,t,i)),new de(s)):new de(s)));if(t==ve.PROCESSOR)throw new Error("InkBuilder processSpline failed for spline",e)}}class et{constructor(){this.queue=Promise.resolve(),this.thenables=[]}then(e,t,i){return this.thenables.push(e),this.queue=this.queue.then(((...t)=>(this.thenables.shift(),e.canceled?Promise.resolve():e(...t)))),t&&this.then((e=>t(e,i))),this}catch(e){return this.queue=this.queue.catch(e),this}cancel(){this.thenables.forEach((e=>e.canceled=!0))}isEmpty(){return 0==this.thenables.length}static async serial(e,t){let i=new et;return e.forEach(((e,s)=>i.then(e,t,s))),i.queue}}class tt extends Ke{constructor(){super(),this.convexHullChainProducer=new be,Object.defineProperty(this,"closed",{get:()=>this.convexHullChainProducer.closed,enumerable:!0}),this.queue=new et}async open(){await this.convexHullChainProducer.open()}close(){this.convexHullChainProducer.close()}onComplete(e){throw new Error("InkBuilderAbstract.onComplete(pathSegment) is abstract and should be implemented")}build(){if(this.buildPhase&&this.phase!=Oe.END)return;let e=this.phase;this.queue.then((()=>(this.buildPhase=e,this.buildSegment()))).then((t=>{this.buildPhase=null,t.phase=e,t.pointerID=this.pointerID,this.onComplete(t),e==Oe.END&&(delete this.phase,delete this.pipeline)}))}async buildChain(){let e=await this.buildSegment();return e.phase=this.phase,e.pointerID=this.pointerID,this.onComplete(e),this.phase==Oe.END&&delete this.phase,e}async buildSegment(){let e={};return this.pathSegment.accumulatedAddition.length>0&&(e.added=await this.processSegment(this.pathSegment.accumulatedAddition,ve.ADDITION,this.pathSegment.last),e.pipeline=this.pipeline,e.added&&(e.added.segment=!0)),this.prediction&&this.pathSegment.lastPrediction.length>0&&(e.predicted=await this.processSegment(this.pathSegment.lastPrediction,ve.PREDICTION,this.pathSegment.last),e.predicted&&(e.predicted.segment=!0)),this.pathSegment.reset(),e}async processSegment(e,t,i){if(this.excludedPipelineStages.includes(Ie.SMOOTHER)||(e=this.smoother.process(e,t,i)),e=this.splineProducer.process(e,t,i))return this.lastPipelineStage==Ie.SPLINE_PRODUCER?e:this.processSpline(e,t,i)}async processSpline(e,t=ve.PROCESSOR,i=!0){t==ve.ADDITION&&(this.pipeline={}),t==ve.ADDITION&&(this.pipeline.spline=e);let s,r=this.splineInterpolator.process(e,t,i);if(this.lastPipelineStage==Ie.SPLINE_INTERPOLATOR)return r;if(r)return t==ve.ADDITION&&(this.pipeline.interpolatedSpline=r),r=this.brushApplier.process(r,t,i),this.lastPipelineStage==Ie.BRUSH_APPLIER?r:(t==ve.ADDITION&&(this.pipeline.shapesPath=r),r=await this.convexHullChainProducer.process(r,t,i),this.lastPipelineStage==Ie.CONVEX_HULL_CHAIN_PRODUCER?r:(t==ve.ADDITION&&(this.pipeline.convexPath=r),t==ve.PREDICTION?r:this.excludedPipelineStages.includes(Ie.POLYGON_MERGER)||(s=this.polygonMerger.process(r,t,i),this.lastPipelineStage!=Ie.POLYGON_MERGER)?(this.excludedPipelineStages.includes(Ie.POLYGON_SIMPLIFIER)||(s=this.polygonSimplifier.process(s,t,i)),new de(s)):new de(s)));if(t==ve.PROCESSOR)throw new Error("InkBuilderAsync processSpline failed for spline",e)}abort(){this.buildPhase=null,this.queue.cancel(),super.abort()}}const it=["position","size","rotation","scale","offset"],st={position:0,size:4,rotation:8,scale:12,offset:16};class rt{static createTreeURI(e,t){return`uim:tree/${t?`${t}/`:""}${e}`}static createStrokeURI(e,t){return`uim:stroke/${t?`${t}/`:""}${e}`}static createSensorDataURI(e,t){return`uim:sensor/${t?`${t}/`:""}${e}`}static createNodeURI(e,t,i){if(!e)throw new Error("inkTree is required");let s="";return i&&(s=`#frag=${i.pointIndexStart},${i.pointIndexEnd}`,0==i.ts&&1==i.tf||(s+=`,${i.ts.toFixed(5)},${i.tf.toFixed(5)}`)),`${rt.createNodeURISchema(e)}/${t}${s}`}static createNodeURISchema(e,t=e.name){return`uim:node${e.id?`/${e.id}`:""}/${t}`}static createNamedEntityURI(e,t){return`uim:ne/${t?`${t}/`:""}${e}`}}class nt{static get SEPARATOR(){return"\n"}#s;constructor(e){let t;if(this.#s=e,"function"==typeof this.getMD5Message)t=nt.Algorithm.MD5;else if("function"==typeof this.buildURI)t=nt.Algorithm.URI;else if(t=nt.Algorithm.GUID,e&&!Q.validate(e))throw new Error(`Identifiable ${e} is not a well formed UUID`);Object.defineProperty(this,"algorithm",{value:t}),Object.defineProperty(this,"id",{get:()=>(this.#s||(this.#s=this.resolveID()),this.#s),set:e=>{if(this.#s)throw new Error("id is immutable");this.#s=e},enumerable:!0})}invalidateID(){if(this.algorithm!=nt.Algorithm.MD5)throw new Error(`Invalidate id is not applicable for ${this.algorithm} algorithm`);this.#s=void 0}resolveID(){if(this.algorithm==nt.Algorithm.MD5){let e="",t=this.getMD5Message();for(let i of t){if(Array.isArray(i))for(let t of i)e+=t,e+="\n";else e+=i;e+="\n"}if(!e)throw new Error("Empty MD5 message container found");return K(e)}return this.algorithm==nt.Algorithm.URI?this.buildURI():Q.generate()}static buildMD5Tokens(e){let t=[];return Object.keys(e).sort().forEach((i=>t.push(i,e[i]))),t}}let at,ot;Object.defineEnum(nt,"Algorithm",["GUID","MD5","URI"]);class lt extends nt{#c;#i;#d;#f;#m;#g=lt.RenderMode.SOURCE_OVER;#y;#P=lt.CompressionType.AUTO;constructor(e,t,i,s){super(t.id),t.id||(t.id=this.id),this.#f=s;let r=new j(t.layout,t.pointProps);Object.defineProperty(this,"target",{get:()=>console.warn("Stroke 'target' property is deprecated. Do not affects Stroke behaviour."),set:e=>console.warn("Stroke 'target' property is deprecated. Do not affects Stroke behaviour.")});let n=!0;Object.defineProperty(this,"layout",{value:t.layout,enumerable:!0}),Object.defineProperty(this,"points",{get:()=>t.points,enumerable:!0}),Object.defineProperty(this,"pointProps",{value:t.pointProps,enumerable:!0}),Object.defineProperty(this,"style",{value:r.style,enumerable:!0}),Object.defineProperty(this,"ts",{value:t.ts,enumerable:!0}),Object.defineProperty(this,"tf",{value:t.tf,enumerable:!0}),Object.defineProperty(this,"stride",{value:t.stride,enumerable:!0}),Object.defineProperty(this,"length",{value:t.length,enumerable:!0}),Object.defineProperty(this,"segmentsCount",{value:t.segmentsCount,enumerable:!0}),Object.defineProperty(this,"color",{get:()=>r.style.color,set:e=>{t.color=e,this.#i&&(this.#i.color=e)},enumerable:!0}),Object.defineProperty(this,"sensorData",{get:()=>this.#f,set:e=>{if(this.#f)throw new Error("sensorData is immutable");this.#f=e}}),Object.defineProperty(this,"spline",{value:t,enumerable:!0}),Object.defineProperty(this,"path",{get:()=>(this.#i||this.buildPath(),this.#i),set:e=>{this.#i=e,this.#i instanceof te&&(this.#i.style=r.style),this.#d=null},enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>(this.#d||(this.#d=this.path.bounds),this.matrix?this.#d.transform(this.matrix).ceil():this.#d),set:e=>this.#d=e,enumerable:!0}),Object.defineProperty(this,"descriptor",{value:{brush:{}},enumerable:!0}),Object.defineProperty(this,"brush",{get:()=>(e||(e=this.descriptor.brush.value),e),set:i=>{if(n||(this.path=null),"string"==typeof i?i=new _e(i):i instanceof ze||i instanceof Ve?i=new _e(i.name,i):i instanceof _e||(i=new _e(i.name,i.value)),i instanceof Ve&&!t.randomSeed)throw new Error("Spline do not provides randomSeed. Raster rendering requires it.");e=null,this.descriptor.brush=i},enumerable:!0}),Object.defineProperty(this,"randomSeed",{get:()=>this.#m,set:e=>{if(this.#m)throw new Error("randomSeed is immutable");this.#m=e},enumerable:!0}),Object.defineProperty(this,"renderMode",{get:()=>this.#g,set:e=>{if(!e)throw new Error("Stroke renderMode is required");if(!_.isValidURL(e))throw new Error(`The renderMode ${e} is not a well formed URI`);this.#g=e}}),Object.defineProperty(this,"blendMode",{get:()=>lt.RenderMode.getBlendMode(this.#g),set:e=>{if(!this.blendMode)throw new Error(`Override user defined renderMode '${this.#g}' is not allowed.`);this.#g=lt.RenderMode.get(e)}}),Object.defineProperty(this,"precisionSchema",{get:()=>this.#y,set:e=>{if(this.#y)throw new Error("precisionSchema is immutable, precisionSchema.update(schema) is an alternative");if(e){if(!(e instanceof class{constructor(e=0){this.precisions=e;for(let e of it)Object.defineProperty(this,e,{get:()=>this.get(e),set:t=>this.set(e,t),enumerable:!0});Object.defineProperty(this,"factors",{get:()=>Object.assign({},...it.map((e=>({[e]:10**this[e]})))),enumerable:!0})}get(e){return this.precisions>>st[e]&15}set(e,t){if(t>15||t<0)throw new Error(`Invalid '${e}' precision value ${t} found. The value must be in the interval [0, 15].`);if(t>this[e])throw new Error(`PrecisionSchema '${e}' update failed. Update value ${t} > ${this[e]} - update value should be less than current value.`);t!=this[e]&&(this.precisions=this.precisions&~(15<<st[e])|t<<st[e])}update(e){it.forEach((t=>{let i=e[t];i<this[t]&&(this[t]=i)}))}decode(){return Object.assign({},...it.map((e=>({[e]:this[e]}))))}static encode(e={}){let t=0;return it.forEach((i=>{let s=e[i]||0;if(s>15||s<0)throw new Error(`Invalid '${i}' precision value ${s} found. The value must be in the interval [0, 15].`);t=t&~(15<<st[i])|s<<st[i]})),t}}))throw new Error("Expected precisionSchema type is PrecisionSchema");this.#y=e,this.#P=lt.CompressionType.COMPUTED}else this.#P=lt.CompressionType.NONE}}),Object.defineProperty(this,"compressionType",{get:()=>this.#P,set:e=>{if(!e)throw new Error("Stroke compressionType is required");if(this.#P==lt.CompressionType.COMPUTED&&e==lt.CompressionType.NONE)throw new Error("compressionType NONE is not applicable for compressed stroke");this.#P=e}}),Object.defineProperty(this,"uri",{get:()=>(this.#c||(this.#c=rt.createStrokeURI(this.id)),this.#c),enumerable:!0}),this.brush=e,this.path=i,this.sensorDataOffset=0,this.sensorDataMapping=[],n=!1}buildPath(){if(this.pathProceessInProgress)throw new Error("Init process in progress. Await init stroke.");at||(at=new Qe),at.configure(this.buildInkBuilderSettings()),this.path=at.processSpline(this.spline)}async init(e){if(this.pathProceessInProgress=!0,ot||(ot=new tt,ot.closed&&await ot.open()),ot.configure(this.buildInkBuilderSettings(e)),this.path=await ot.processSpline(this.spline),Object.keys(ot.allData).length>0){let{interpolatedSpline:e,shapesPath:t,convexPath:i}=ot.allData;this.pipeline={},e&&(this.pipeline.interpolatedSpline=e),t&&(this.pipeline.shapesPath=t),i&&(this.pipeline.convexPath=i)}delete this.pathProceessInProgress}buildInkBuilderSettings(e){return lt.onPipeline?lt.onPipeline(this):Object.assign({},{brush:this.brush,layout:this.layout,pathPointProps:this.pointProps},e)}invalidateBounds(){this.#d=null}clone(e=!0,t=!1){let i;this.#i&&(i=e?this.#i:this.#i.clone());let s=this.spline.clone();t&&(s.id=this.id);let r=new lt(this.descriptor.brush,s,i,this.sensorData);return r.randomSeed=this.#m,r.renderMode=this.#g,r.sensorDataOffset=this.sensorDataOffset,r.sensorDataMapping=this.sensorDataMapping.clone(),r}getSensorPoint(e){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);let t;if(0==this.sensorDataOffset&&e>0&&e--,this.sensorData){let i=this.sensorData.inkStream;if(i){let s;this.sensorDataMapping.length>0?s=e>=this.sensorDataMapping.length?this.sensorDataMapping.last:this.sensorDataMapping[e]:(s=this.sensorDataOffset+e,s>=i.length&&(s=i.length-1)),t=i.get(s),t.index=s,t.timespan=t.timestamp,t.timestamp+=this.sensorData.created}}return t}getPoint(e){return this.spline.getPoint(e)}setPoint(e,t){let i=e*this.stride;this.layout.forEach(((e,s)=>this.points[i+s]=t.getProperty(e)))}pointAt(e){return this.getPoint(e)}getSegment(e){return this.spline.getSegment(e)}getAverageWidth(){let e=0;if(this.layout.includes(w.Property.SIZE)){let t=0;for(let e=0;e<this.length;e++)t+=this.getPointRef(e).size;e=t/this.length}else e=this.pointProps.size;return e}split(e){let t=e.map((e=>this.slice(e)));return t.includes(this)?void 0:t}slice(e){if(0==e.pointIndexStart&&e.pointIndexEnd+1==this.length&&e.ts==this.ts&&e.tf==this.tf)return this;{let t=this.spline.slice(e),i=new lt(this.descriptor.brush,t,void 0,this.sensorData);if(i.randomSeed=this.#m,i.renderMode=this.#g,this.sensorData){let t=e.pointIndexStart;if(0==this.sensorDataOffset&&e.pointIndexStart>0&&(t=e.pointIndexStart-1),i.sensorDataOffset=this.sensorDataOffset+t,this.sensorDataMapping.length>0){let s;s=e.pointIndexEnd>this.sensorDataMapping.length?this.sensorDataMapping.length:0==i.sensorDataOffset?e.pointIndexEnd:e.pointIndexEnd+1,i.sensorDataMapping=this.sensorDataMapping.slice(t,s)}else i.sensorDataMapping=[]}return i}}transform(e){if(e||(e=this.matrix,this.matrix=null),e){if(this.spline.transform(e),this.#i&&this.path.transform(e),this.pipeline){let{interpolatedSpline:t,shapesPath:i,convexPath:s}=this.pipeline;t&&t.transform(e),i&&i.transform(e),s&&s.transform(e)}this.#P!=lt.CompressionType.NONE&&(this.#y=void 0,this.#P=lt.CompressionType.AUTO),this.#d=null}}setTransform(e){this.matrix=e}static createInstance(e,t,i,s={},r,n=0,a=1){let o=s.id,l=s.color;o&&delete s.id,l&&(delete s.color,s=Object.assign({},s),i.includes(w.Property.RED)||(s.red=l.red),i.includes(w.Property.GREEN)||(s.green=l.green),i.includes(w.Property.BLUE)||(s.blue=l.blue),i.includes(w.Property.ALPHA)||(s.alpha=l.alpha));let h=ne.createSharedInstance(i,t,s,n,a);h.id=o;let u=new lt(e,h);return u.randomSeed=r,u}static validatePath(e){if(!e)return!1;if(0==e.length)return!1;if(e instanceof de)return!0;if(Array.isArray(e))throw new Error("path should be instance of InkPath2D");let t=!1,i=0,s=!1,{size:r,red:n,green:a,blue:o,alpha:l}=e.pointProps;if(!(e instanceof te)){let t=e.points.length,r=e.layout.length;s=0==t||t<4*r,i=t%r}return 0!=i?console.error(`The points array (length: ${e.points.length}) does not refer to provided layout (${e.layout.map((e=>e.name)).join(", ")})`):s?console.error("Less than needed minimum of points passed (At least 4 points are needed to define a path)!"):!e.layout.includes(w.Property.SIZE)&&isNaN(r)?console.error("Either the size property must be set or the path layout must include a SIZE property"):!e.layout.includes(w.Property.RED)&&isNaN(n)?console.error("Either the color property must be set or the path layout must include a RED property"):!e.layout.includes(w.Property.GREEN)&&isNaN(a)?console.error("Either the color property must be set or the path layout must include a GREEN property"):!e.layout.includes(w.Property.BLUE)&&isNaN(o)?console.error("Either the color property must be set or the path layout must include a BLUE property"):!e.layout.includes(w.Property.ALPHA)&&isNaN(l)?console.error("Either the color property must be set or the path layout must include a ALPHA property"):t=!0,t}static decodeInkPath(e){if("InkPath2D"==e.type)return de.fromJSON(e);if("InterpolatedSpline"==e.type)return te.fromJSON(e);throw new Error(`Decode ink path faild. Cannot identify type: ${e.type}`)}}lt.RenderMode=Object.assign({},...Object.keys(qe).map((e=>({[e]:`will://rasterization/3.0/blend-mode/${_.getPropName(e,!0)}`})))),lt.RenderMode.get=e=>lt.RenderMode[_.getEnumValueName(e.replace(/-/g,"_"))],lt.RenderMode.getBlendMode=e=>qe[Object.keys(lt.RenderMode).filter((t=>lt.RenderMode[t]==e)).first],lt.Target={},Object.defineProperty(lt.Target,"2D",{get:()=>console.warn("Stroke 'Target[2D]' enum is deprecated")}),Object.defineProperty(lt.Target,"GL",{get:()=>console.warn("Stroke 'Target[GL]' enum is deprecated")}),Object.defineEnum(lt,"CompressionType",["AUTO","NONE","COMPUTED"]);class ht{#s;constructor(e,t,i,s,r,n,a,o){this.strokeID=e,t<s&&1==i&&(t++,i=0),s>t&&0==r&&(s--,r=1),this.segmentIndexStart=t,this.segmentIndexEnd=s,this.ts=i,this.tf=r,Object.defineProperty(this,"id",{get:()=>(this.#s||(this.#s=`${e}::${t}-${s}::${i.toFixed(5)}-${r.toFixed(5)}`),this.#s)}),this.bounds=n,this.shapesPath=o,this.splineParameters=a}toString(){return`node[${this.strokeID}](${this.segmentIndexStart}, ${this.ts}, ${this.segmentIndexEnd}, ${this.tf}) - ${this.bounds.toString()}`}toJSON(){return{strokeID:this.strokeID,segmentIndexStart:this.segmentIndexStart,segmentIndexEnd:this.segmentIndexEnd,ts:this.ts,tf:this.tf}}static fromJSON(e,t,i,s){return new ht(e.strokeID,e.segmentIndexStart,e.ts,e.segmentIndexEnd,e.tf,t,i,s)}}class ut extends class{constructor(e=!1){let t;this.splitStrokes=e,Object.defineProperty(this,"context",{get:()=>{if(!t)throw new Error("Spatial context not found. Set value first.");return t},set:e=>{if(!e)throw new Error("Spatial context value is required");t=e},enumerable:!0}),this.splineInterpolator=new re}processStrokePart(e,t,i,s){let r=e.splineParameters,n=e.shapesPath;1==n.length&&n.push(n[0]);let a=r[0],o=n[0],l=o.bounds;for(let h=1;h<n.length;h++){let u=n[h].bounds;if(u.union(l).intersects(s)){n[h].union(o).intersects(t)&&(this.splitStrokes?this.split(e,t,i,o,n[h],a,r[h]):this.selected.add(e.strokeID))}a=r[h],o=n[h],l=u}}split(e,t,i,s,r,n,a){let o,l,h=this.context.getStroke(e.strokeID),u=h.spline,p=u.segmentsCount-1,d=s.intersects(t),f=r.intersects(t);if(d&&f)0==n.segmentIndex&&n.t==u.ts&&(o=n),a.segmentIndex==p&&a.t==u.tf&&(l=a);else if(d)0==n.segmentIndex&&n.t==u.ts&&(o=n),l=this.seekNonIntersectingPartFromEnd(h,t,r,n,a);else if(f)o=this.seekNonIntersectingPartFromStart(h,t,s,n,a),a.segmentIndex==p&&a.t==u.tf&&(l=a);else{let e=this.seekNonIntersectingPartFromStart(h,t,s,n,a),i=this.seekNonIntersectingPartFromEnd(h,t,r,e,a);(e.segmentIndex==i.segmentIndex&&e.t<i.t||e.segmentIndex<i.segmentIndex)&&(o=e,l=i)}if(o||l){let e=this.splitPoints[h.id];e||(e=[],this.splitPoints[h.id]=e),o&&e.push(new c(o,i,!1)),l&&e.push(new c(l,i,!0))}}seekNonIntersectingPartFromStart(e,t,i,s,r){let n=s,a=r,o=s,l=this.context.getBrushApplier(e.id);for(;p.areDistantEnough(n,a,this.splineParameterDistanceThreshold);){let s=p.calcMiddleOfSegment(n,a),r=this.splineInterpolator.calculateInterpolatedPoint(e.spline,s.segmentIndex,s.t);l.applyBrush(r).union(i).intersects(t)?a=s:(n=s,o=s)}return o}seekNonIntersectingPartFromEnd(e,t,i,s,r){let n=s,a=r,o=r,l=this.context.getBrushApplier(e.id);for(;p.areDistantEnough(n,a,this.splineParameterDistanceThreshold);){let s=p.calcMiddleOfSegment(n,a),r=this.splineInterpolator.calculateInterpolatedPoint(e.spline,s.segmentIndex,s.t);l.applyBrush(r).union(i).intersects(t)?n=s:(a=s,o=s)}return o}reset(e){e&&(this.context=e),this.fragments={},this.selected=new Set,this.splitStrokes&&(this.splitPoints={}),this.context.tree.canvas&&this.context.tree.canvas.refresh()}}{splineParameterDistanceThreshold=.01;constructor(e=ut.Mode.WHOLE_STROKE){super(e!=ut.Mode.WHOLE_STROKE),this.mode=e}async intersect(e,t){let i,s,r;if(e instanceof lt){let t=e.pipeline||{};t.shapesPath?r=t.shapesPath:(i=t.interpolatedSpline||this.splineInterpolator.process(e.spline),s=this.context.nodeProducer.getBrushApplier(e.brush))}else{if(!t)throw new Error("brush expected");if(!(t instanceof ze))throw new Error("brush should be Brush2D instance");if(e instanceof te)s=this.context.nodeProducer.getBrushApplier(t),i=e;else{if(!(e instanceof ne))throw new Error("Expected input should be instance of Stroke, InterpolatedSpline, Spline");i=this.splineInterpolator.process(e),s=this.context.nodeProducer.getBrushApplier(t)}}return r||(r=s.process(i)),this.reset(),this.context.tree.canvas&&this.context.tree.canvas.fillShape(r),await this.processNodes(r),this.mode==ut.Mode.PARTIAL_STROKE&&this.buildFragments(),{type:"INTERSECTION",intersected:this.fragments,selected:Array.from(this.selected),length:Object.keys(this.fragments).length+this.selected.size}}async processNodes(e){if(0==e.length)return;1==e.length&&e.push(e[0]);let t=e[0],i=t.bounds,s={},r=this.mode==ut.Mode.PARTIAL_STROKE&&this.splitPointsProducer;for(let n=1;n<e.length;n++){let a=e[n].bounds,o=a.union(i),l=this.context.tree.search(o);if(l.length>0){let i=e[n].union(t),a=n-1;if(r)for(let e of l)s[e.id]||(s[e.id]=[]),s[e.id].push({node:e,eraserHull:i,eraserSegmentIndex:a,eraserSegmentBounds:o});else for(let e of l)this.processStrokePart(e,i,a,o)}t=e[n],i=a}if(r){let e=[];Object.values(s).forEach((t=>{let i=this.encodeNodeProcessingInfo(t);e.push(i)})),e.length>0&&(this.splitPoints=await this.splitPointsProducer.build(e))}}buildFragments(){for(let e in this.splitPoints){let t=this.context.getStroke(e),i=this.convertSplitPointsToFragments(t);0==i.length?this.selected.add(t.id):this.fragments[t.id]=i}}convertSplitPointsToFragments(e){let t=[],i=this.splitPoints[e.id];if(0==i.length)return t;i.sort(c.compare);let s,r,n,a=new Set,o=e.spline,l=!0;i[0].on?(n=1,s=i[0].splineParameter):(n=0,s=new p(0,o.ts));for(let e=n;e<i.length;e++){let n=i[e];if(n.on)a.delete(n.segmentIndex),0==a.size&&(s=n.splineParameter,l=!0);else if(a.add(n.segmentIndex),l&&(r=n.splineParameter,l=!1,s.segmentIndex!=r.segmentIndex||s.t!=r.t)){let e=ee.getInstance(o,s,r);t.push(e)}}if(l&&(r=new p(o.segmentsCount-1,o.tf),s.segmentIndex!=r.segmentIndex||s.t!=r.t)){let e=ee.getInstance(o,s,r);t.push(e)}return t}encodeNodeProcessingInfo(e){let t={splineParameterDistanceThreshold:this.splineParameterDistanceThreshold,input:[]};for(let i of e){if(!t.target){let e=this.context.getStroke(i.node.strokeID);e.spline.id=e.id,t.target={stroke:{brush:e.brush.toJSON(),spline:e.spline.toJSON()},bounds:i.node.bounds.toJSON(),shapesPath:i.node.shapesPath.map((e=>e.toJSON())),splineParameters:i.node.splineParameters.map((e=>e.toJSON()))}}t.input.push({node:i.node.toJSON(),eraserHull:i.eraserHull.toJSON(),eraserSegmentIndex:i.eraserSegmentIndex,eraserSegmentBounds:i.eraserSegmentBounds.toJSON()})}return t}static decodeNodeProcessingInfo(e){let{target:t,input:i,splineParameterDistanceThreshold:s}=e,r=ze.fromJSON(t.stroke.brush),n=ne.fromJSON(t.stroke.spline),a=new lt(r,n),o={bounds:V.fromRect(t.bounds),shapesPath:t.shapesPath.map((e=>W.fromJSON(e))),splineParameters:t.splineParameters.map((e=>p.fromJSON(e)))};return i=i.map((e=>({node:ht.fromJSON(e.node,o.bounds,o.splineParameters,o.shapesPath),eraserHull:W.fromJSON(e.eraserHull),eraserSegmentIndex:e.eraserSegmentIndex,eraserSegmentBounds:V.fromRect(e.eraserSegmentBounds)}))),{stroke:a,input:i,splineParameterDistanceThreshold:s}}}Object.defineEnum(ut,"Mode",["WHOLE_STROKE","PARTIAL_STROKE"]);let pt={palettes:{}};const ct=["AliceBlue","#F0F8FF","AntiqueWhite","#FAEBD7","Aqua","#00FFFF","Aquamarine","#7FFFD4","Azure","#F0FFFF","Beige","#F5F5DC","Bisque","#FFE4C4","Black","#000000","BlanchedAlmond","#FFEBCD","Blue","#0000FF","BlueViolet","#8A2BE2","Brown","#A52A2A","BurlyWood","#DEB887","CadetBlue","#5F9EA0","Chartreuse","#7FFF00","Chocolate","#D2691E","Coral","#FF7F50","CornflowerBlue","#6495ED","Cornsilk","#FFF8DC","Crimson","#DC143C","Cyan","#00FFFF","DarkBlue","#00008B","DarkCyan","#008B8B","DarkGoldenRod","#B8860B","DarkGray","#A9A9A9","DarkGreen","#006400","DarkKhaki","#BDB76B","DarkMagenta","#8B008B","DarkOliveGreen","#556B2F","DarkOrange","#FF8C00","DarkOrchid","#9932CC","DarkRed","#8B0000","DarkSalmon","#E9967A","DarkSeaGreen","#8FBC8F","DarkSlateBlue","#483D8B","DarkSlateGray","#2F4F4F","DarkTurquoise","#00CED1","DarkViolet","#9400D3","DeepPink","#FF1493","DeepSkyBlue","#00BFFF","DimGray","#696969","DodgerBlue","#1E90FF","FireBrick","#B22222","FloralWhite","#FFFAF0","ForestGreen","#228B22","Fuchsia","#FF00FF","Gainsboro","#DCDCDC","GhostWhite","#F8F8FF","Gold","#FFD700","GoldenRod","#DAA520","Gray","#808080","Green","#008000","GreenYellow","#ADFF2F","HoneyDew","#F0FFF0","HotPink","#FF69B4","IndianRed","#CD5C5C","Indigo","#4B0082","Ivory","#FFFFF0","Khaki","#F0E68C","Lavender","#E6E6FA","LavenderBlush","#FFF0F5","LawnGreen","#7CFC00","LemonChiffon","#FFFACD","LightBlue","#ADD8E6","LightCoral","#F08080","LightCyan","#E0FFFF","LightGoldenRodYellow","#FAFAD2","LightGray","#D3D3D3","LightGreen","#90EE90","LightPink","#FFB6C1","LightSalmon","#FFA07A","LightSeaGreen","#20B2AA","LightSkyBlue","#87CEFA","LightSlateGray","#778899","LightSteelBlue","#B0C4DE","LightYellow","#FFFFE0","Lime","#00FF00","LimeGreen","#32CD32","Linen","#FAF0E6","Magenta","#FF00FF","Maroon","#800000","MediumAquaMarine","#66CDAA","MediumBlue","#0000CD","MediumOrchid","#BA55D3","MediumPurple","#9370DB","MediumSeaGreen","#3CB371","MediumSlateBlue","#7B68EE","MediumSpringGreen","#00FA9A","MediumTurquoise","#48D1CC","MediumVioletRed","#C71585","MidnightBlue","#191970","MintCream","#F5FFFA","MistyRose","#FFE4E1","Moccasin","#FFE4B5","NavajoWhite","#FFDEAD","Navy","#000080","OldLace","#FDF5E6","Olive","#808000","OliveDrab","#6B8E23","Orange","#FFA500","OrangeRed","#FF4500","Orchid","#DA70D6","PaleGoldenRod","#EEE8AA","PaleGreen","#98FB98","PaleTurquoise","#AFEEEE","PaleVioletRed","#DB7093","PapayaWhip","#FFEFD5","PeachPuff","#FFDAB9","Peru","#CD853F","Pink","#FFC0CB","Plum","#DDA0DD","PowderBlue","#B0E0E6","Purple","#800080","RebeccaPurple","#663399","Red","#FF0000","RosyBrown","#BC8F8F","RoyalBlue","#4169E1","SaddleBrown","#8B4513","Salmon","#FA8072","SandyBrown","#F4A460","SeaGreen","#2E8B57","SeaShell","#FFF5EE","Sienna","#A0522D","Silver","#C0C0C0","SkyBlue","#87CEEB","SlateBlue","#6A5ACD","SlateGray","#708090","Snow","#FFFAFA","SpringGreen","#00FF7F","SteelBlue","#4682B4","Tan","#D2B48C","Teal","#008080","Thistle","#D8BFD8","Tomato","#FF6347","Turquoise","#40E0D0","Violet","#EE82EE","Wheat","#F5DEB3","White","#FFFFFF","WhiteSmoke","#F5F5F5","Yellow","#FFFF00","YellowGreen","#9ACD32"],dt={red:["LightSalmon","Salmon","DarkSalmon","LightCoral","IndianRed","Crimson","FireBrick","Red","DarkRed"],orange:["Coral","Tomato","OrangeRed","Gold","Orange","DarkOrange"],yellow:["LightYellow","LemonChiffon","LightGoldenRodYellow","PapayaWhip","Moccasin","PeachPuff","PaleGoldenRod","Khaki","DarkKhaki","Yellow"],green:["LawnGreen","Chartreuse","LimeGreen","Lime","ForestGreen","Green","DarkGreen","GreenYellow","YellowGreen","SpringGreen","MediumSpringGreen","LightGreen","PaleGreen","DarkSeaGreen","MediumSeaGreen","SeaGreen","Olive","DarkOliveGreen","OliveDrab"],cyan:["LightCyan","Cyan","Aqua","Aquamarine","MediumAquaMarine","PaleTurquoise","Turquoise","MediumTurquoise","DarkTurquoise","LightSeaGreen","CadetBlue","DarkCyan","Teal"],blue:["PowderBlue","LightBlue","LightSkyBlue","SkyBlue","DeepSkyBlue","LightSteelBlue","DodgerBlue","CornflowerBlue","SteelBlue","RoyalBlue","Blue","MediumBlue","DarkBlue","Navy","MidnightBlue","MediumSlateBlue","SlateBlue","DarkSlateBlue"],purple:["Lavender","Thistle","Plum","Violet","Orchid","Fuchsia","Magenta","MediumOrchid","MediumPurple","BlueViolet","DarkViolet","DarkOrchid","DarkMagenta","Purple","RebeccaPurple","Indigo"],pink:["Pink","LightPink","HotPink","DeepPink","PaleVioletRed","MediumVioletRed"],white:["White","Snow","HoneyDew","MintCream","Azure","AliceBlue","GhostWhite","WhiteSmoke","SeaShell","Beige","OldLace","FloralWhite","Ivory","AntiqueWhite","Linen","LavenderBlush","MistyRose"],gray:["Gainsboro","LightGray","Silver","DarkGray","Gray","DimGray","LightSlateGray","SlateGray","DarkSlateGray","Black"],brown:["Cornsilk","BlanchedAlmond","Bisque","NavajoWhite","Wheat","BurlyWood","Tan","RosyBrown","SandyBrown","GoldenRod","Peru","DarkGoldenRod","Chocolate","SaddleBrown","Sienna","Brown","Maroon"]};let ft={};function mt(e,t){return ft[e]||(ft[e]=B.fromColor(t)),ft[e]}for(let e=0;e<ct.length;e+=2){let t=_.getEnumValueName(ct[e]);Object.defineProperty(pt,t,{get:()=>mt(t,ct[e+1]),enumerable:!0})}for(let e in dt){let t=dt[e];pt.palettes[e]={scale:t};for(let i=0;i<t.length;i++){let s=_.getEnumValueName(t[i]);Object.defineProperty(pt.palettes[e],s,{get:()=>pt[s],enumerable:!0})}}class gt extends class{constructor(e){Object.defineProperty(this,"ctx",{value:e,enumerable:!0})}clearCanvas(){this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height)}setTransform(e){this.ctx.setTransform(e.a,e.b,e.c,e.d,e.tx,e.ty)}drawRect(e,t=pt.GRAY.toRGBA(.3)){this.ctx.strokeStyle=t.toString(),this.ctx.strokeRect(e.left,e.top,e.width,e.height)}fillRect(e,t=pt.GRAY.toRGBA(.3)){this.ctx.fillStyle=t.toString(),this.ctx.fillRect(e.left,e.top,e.width,e.height)}drawPoint(e,t=5,i=pt.BLACK){this.ctx.beginPath(),this.ctx.arc(e.x,e.y,t,0,2*Math.PI),this.renderStyle({type:"stroke",style:i})}fillPoint(e,t=5,i=pt.BLACK){this.ctx.beginPath(),this.ctx.arc(e.x,e.y,t,0,2*Math.PI),this.renderStyle({type:"fill",style:i})}drawEllipse(e,t,i,s=pt.BLACK){this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,t,i,0,0,2*Math.PI),this.renderStyle({type:"stroke",style:s})}fillEllipse(e,t,i,s=pt.BLACK){this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,t,i,0,0,2*Math.PI),this.renderStyle({type:"fill",style:s})}drawShape(e,t=pt.DARK_MAGENTA.toRGBA(.5)){this.renderShape(e,{type:"stroke",style:t})}fillShape(e,t=pt.ORANGE.toRGBA(.6)){this.renderShape(e,{type:"fill",style:t})}renderShape(e,t={}){if(e instanceof Y)this.ctx.beginPath(),this.renderPath(e);else if(e instanceof W)this.renderPolygon(e);else{if(!(e instanceof ce))throw new Error("Unexpected shape type found");this.ctx.beginPath();for(let t of e)this.renderPolygon(t,{segment:!0})}this.renderStyle(t)}renderPolygon(e,t={}){t.segment||this.ctx.beginPath(),this.renderPath(e.shape),e.holes.forEach((t=>this.renderPath(t,{holesDirection:e.holesDirection}))),t.segment||this.renderStyle(t)}renderPath(e,t={}){if(!t.holesDirection||t.holesDirection==W.PointsDirection.CLOCKWISE){this.ctx.moveTo(e.getPointX(0),e.getPointY(0));for(let t=1;t<e.length;t++)this.ctx.lineTo(e.getPointX(t),e.getPointY(t))}else{this.ctx.moveTo(e.getPointX(e.length-1),e.getPointY(e.length-1));for(let t=e.length-2;t>=0;t--)this.ctx.lineTo(e.getPointX(t),e.getPointY(t))}this.ctx.closePath(),this.renderStyle(t)}renderStyle(e){if(e.type){if("fill"!=e.type&&"stroke"!=e.type)throw new Error("Option type should be oneof(stroke, fill)");e.style&&(this.ctx[`${e.type}Style`]=e.style instanceof B?e.style.toString():e.style),this.ctx[e.type]()}}}{constructor(e){super(e.getContext("2d"))}clear(){let e=this.ctx.canvas.toRect().transform(this.ctx.getTransform().invert());this.ctx.clearRect(e.left,e.top,e.width,e.height),this.clearCanvas()}refresh(){if(this.suppressRefresh)return;let e=[];gt.allocateSegments(e,this.data,0),this.clear(),this.drawRange(e)}drawRange(e){e.forEach((e=>this.drawRect(e.bounds,pt.MAGENTA)))}static allocateSegments(e,t,i){if(t&&(t.bounds&&e.push(t),t.children))if(10!==i)for(let s=0;s<t.children.length;s++)gt.allocateSegments(e,t.children[s],i+1);else console.warn("depth 10")}static getInstance(e,t){if(!e)return;let i=new gt(e);return Object.defineProperty(i,"data",{get:()=>t.data,enumerable:!0}),i}}class yt extends u{constructor(...e){let t;super(...e),"undefined"!=typeof document&&("loading"==document.readyState?addEventListener("DOMContentLoaded",(e=>t=gt.getInstance(document.getElementById("rbush"),this))):t=gt.getInstance(document.getElementById("rbush"),this)),Object.defineProperty(this,"canvas",{get:()=>this.debug?t:null,enumerable:!0})}toBBox(e){return{minX:e.bounds.left,minY:e.bounds.top,maxX:e.bounds.right,maxY:e.bounds.bottom}}compareMinX(e,t){return e.bounds.x-t.bounds.x}compareMinY(e,t){return e.bounds.y-t.bounds.y}search(e){return super.search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom})}find(e,t=this.data,i=0,s=[]){if(t){if(t.stroke){let i=!0;Object.keys(e).forEach((s=>{i=i&&t[s]==e[s]})),i&&s.push(t)}if(t.children){if(6!==i){for(let r=0;r<t.children.length;r++)this.find(e,t.children[r]||null,i+1,s);return s}console.warn("depth 6")}}}load(e){Array.isArray(e)||(e=[e]),0!=e.length&&(super.load(e),this.canvas&&this.canvas.refresh())}unload(e){Array.isArray(e)||(e=[e]),e.forEach((e=>this.remove(e))),this.canvas&&this.canvas.refresh()}}class Pt{constructor(e){this.tree=e,this.brushAppliers={},this.splineInterpolator=new re(!1,!0)}getBrushApplier(e){return this.brushAppliers[e.name]||(this.brushAppliers[e.name]=new fe(e)),this.brushAppliers[e.name]}buildStrokeNodes(e){let t,i,s=[],r=0,n=0,a=0,o=0,l=0,{interpolatedSpline:h,shapesPath:u}=e.pipeline||{};if(delete e.pipeline,!h||!u){let t=this.getBrushApplier(e.brush);h=this.splineInterpolator.process(e.spline),u=t.process(h)}if(0==u.length)return s;let p=[],c=[];for(let d=0;d<u.length;d++){let f=h.splineParameters[d],m=u[d].bounds;0==r?(n=f.segmentIndex,o=f.t,i=m):this.mustEndCurrentGroup(r,m,i)?(s.push(new ht(e.id,n,o,a,l,i,p,c)),p=[p.last],c=[c.last],n=a,o=l,i=m.union(t),r=1):i=this.fragmentBounds,p.push(f),c.push(u[d]),r++,t=m,a=f.segmentIndex,l=f.t}return s.push(new ht(e.id,n,o,a,l,i,p,c)),this.tree.load(s),s}mustEndCurrentGroup(e,t,i){if(delete this.fragmentBounds,e>50)return!0;let s=t.union(i);return e>1&&s.area>1e4||(!!(e>20&&Pt.isTooSquare(s))||(this.fragmentBounds=s,!1))}static isTooSquare(e){let t=e.width/e.height;return t>.2&&t<5}}class bt{constructor(){this.tree=new yt,this.nodeProducer=new Pt(this.tree),this.strokes={},this.nodes={}}getNodes(e){return this.nodes[e]}getStroke(e){return this.strokes[e]}getBrushApplier(e){return this.nodeProducer.getBrushApplier(this.strokes[e].brush)}add(e){if(!(e.brush instanceof Ve)){if(this.strokes[e.id])throw new Error(`SpatialContext stroke with id ${e.id} is already available`);this.strokes[e.id]=e,this.nodes[e.id]=this.nodeProducer.buildStrokeNodes(e)}}reload(e){this.tree.unload(this.nodes[e.id]),this.nodes[e.id]=this.nodeProducer.buildStrokeNodes(e)}remove(e){let t="string"==typeof e?e:e.id;this.tree.unload(this.nodes[t]),delete this.nodes[t],delete this.strokes[t]}replace(e,t){t.forEach((e=>this.add(e))),this.remove(e)}clone(e){let t=new bt;t.nodeProducer.brushAppliers=this.nodeProducer.brushAppliers;let i=[];for(let s in this.strokes){let r=e.getStroke(s);if(!r)throw new Error(`Provided ink model do not provides stroke with id ${s}`);t.strokes[s]=r,t.nodes[s]=this.nodes[s].slice(),i=i.concat(t.nodes[s])}return t.tree.load(i),t}reset(){this.strokes={},this.nodes={},this.tree.clear()}}(class extends class{constructor(){this.worker,this.transferables=[]}async recieve(e){let t;"INIT"==e.action?(this.worker=e.worker,t=await this.init(e)):t=await this.process(e),t.worker=this.worker,this.send(t)}send(e){self.postMessage(e,this.transferables),this.transferables.length=0}async init(e){return e}async process(e){throw new Error("ThreadProcessor.process(message) is abstract and should be implemented")}static async connect(...e){let t=new this(...e);if("undefined"==typeof self){const e=await import("worker_threads"),{parentPort:t,workerData:i}=e;global.self=t,self.name=i.name,self.data=i}self.on("message",(async e=>await t.recieve(e)))}}{constructor(){super()}process(e){let t={action:e.action,actionID:e.actionID};switch(e.action){case"BUILD":{let{stroke:i,input:s,splineParameterDistanceThreshold:r}=ut.decodeNodeProcessingInfo(e.data),n=this.build(i,s,r);t.strokeID=n.strokeID,n.splitPoints&&(t.splitPoints=n.splitPoints.map((e=>e.toJSON())));break}default:throw new Error(`Unknow data action found: ${e.action}`)}return t}build(e,t,i){let s=t.map((e=>e.node)),r=new bt;r.strokes[e.id]=e,r.nodes[e.id]=s;let n=new ut(ut.Mode.PARTIAL_STROKE);n.splineParameterDistanceThreshold=i,n.reset(r);for(let e of t)n.processStrokePart(e.node,e.eraserHull,e.eraserSegmentIndex,e.eraserSegmentBounds);return{strokeID:e.id,splitPoints:n.splitPoints[e.id]}}}).connect();