laymur 0.0.6 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,3689 @@
1
- import{Vector2 as t,Box2 as i,MathUtils as n,Scene as s,OrthographicCamera as o,Object3D as r,PlaneGeometry as e,MeshBasicMaterial as h,FrontSide as l,Mesh as u,CanvasTexture as a,Texture as c}from"three";function d(){return new v}var v=function(){function t(){this.index={},this.array=[]}return t.prototype.size=function(){return this.array.length},t.prototype.empty=function(){return 0===this.array.length},t.prototype.itemAt=function(t){return this.array[t]},t.prototype.contains=function(t){return void 0!==this.index[t.id()]},t.prototype.find=function(t){var i=this.index[t.id()];return void 0===i?void 0:this.array[i]},t.prototype.setDefault=function(t,i){var n=this.index[t.id()];if(void 0===n){var s=new f(t,i());return this.index[t.id()]=this.array.length,this.array.push(s),s}return this.array[n]},t.prototype.insert=function(t,i){var n=new f(t,i),s=this.index[t.id()];return void 0===s?(this.index[t.id()]=this.array.length,this.array.push(n)):this.array[s]=n,n},t.prototype.erase=function(t){var i=this.index[t.id()];if(void 0!==i){this.index[t.id()]=void 0;var n=this.array[i],s=this.array.pop();return n!==s&&(this.array[i]=s,this.index[s.first.id()]=i),n}},t.prototype.copy=function(){for(var i=new t,n=0;n<this.array.length;n++){var s=this.array[n].copy();i.array[n]=s,i.index[s.first.id()]=n}return i},t}(),f=function(){function t(t,i){this.first=t,this.second=i}return t.prototype.copy=function(){return new t(this.first,this.second)},t}(),w=function(){function t(t){void 0===t&&(t=""),this.t=0,this.i=null,this.o=p++,this.h=t}return t.prototype.id=function(){return this.o},t.prototype.name=function(){return this.h},t.prototype.setName=function(t){this.h=t},t.prototype.context=function(){return this.i},t.prototype.setContext=function(t){this.i=t},t.prototype.value=function(){return this.t},t.prototype.setValue=function(t){this.t=t},t.prototype.plus=function(t){return new b(this,t)},t.prototype.minus=function(t){return new b(this,"number"==typeof t?-t:[-1,t])},t.prototype.multiply=function(t){return new b([t,this])},t.prototype.divide=function(t){return new b([1/t,this])},t.prototype.toJSON=function(){return{name:this.h,value:this.t}},t.prototype.toString=function(){return this.i+"["+this.h+":"+this.t+"]"},t}(),p=0,b=function(){function t(){var t=m(arguments);this.l=t.terms,this.u=t.constant}return t.prototype.terms=function(){return this.l},t.prototype.constant=function(){return this.u},t.prototype.value=function(){for(var t=this.u,i=0,n=this.l.size();i<n;i++){var s=this.l.itemAt(i);t+=s.first.value()*s.second}return t},t.prototype.plus=function(i){return new t(this,i)},t.prototype.minus=function(i){return new t(this,"number"==typeof i?-i:[-1,i])},t.prototype.multiply=function(i){return new t([i,this])},t.prototype.divide=function(i){return new t([1/i,this])},t.prototype.isConstant=function(){return 0==this.l.size()},t.prototype.toString=function(){var t=this.l.array.map((t=>t.second+"*"+t.first)).join(" + ");return this.isConstant()||0===this.u||(t+=" + "),t+this.u},t}();function m(t){for(var i=0,n=()=>0,s=d(),o=0,r=t.length;o<r;++o){var e=t[o];if("number"==typeof e)i+=e;else if(e instanceof w)s.setDefault(e,n).second+=1;else if(e instanceof b){i+=e.constant();for(var h=0,l=(v=e.terms()).size();h<l;h++){var u=v.itemAt(h);s.setDefault(u.first,n).second+=u.second}}else{if(!(e instanceof Array))throw Error("invalid Expression argument: "+e);if(2!==e.length)throw Error("array must have length 2");var a=e[0],c=e[1];if("number"!=typeof a)throw Error("array item 0 must be a number");if(c instanceof w)s.setDefault(c,n).second+=a;else{if(!(c instanceof b))throw Error("array item 1 must be a variable or expression");var v;for(i+=c.constant()*a,h=0,l=(v=c.terms()).size();h<l;h++)u=v.itemAt(h),s.setDefault(u.first,n).second+=u.second*a}}}return{terms:s,constant:i}}var y,g=(()=>{function t(){}return t.create=(t,i,n,s)=>{void 0===s&&(s=1);var o=0;return o+=1e6*Math.max(0,Math.min(1e3,t*s)),(o+=1e3*Math.max(0,Math.min(1e3,i*s)))+Math.max(0,Math.min(1e3,n*s))},t.clip=i=>Math.max(0,Math.min(t.required,i)),t.required=t.create(1e3,1e3,1e3),t.strong=t.create(1,0,0),t.medium=t.create(0,1,0),t.weak=t.create(0,0,1),t})();(t=>{t[t.Le=0]="Le",t[t.Ge=1]="Ge",t[t.Eq=2]="Eq"})(y||(y={}));var S,E=function(){function t(t,i,n,s){void 0===s&&(s=g.required),this.o=C++,this.v=i,this.p=g.clip(s),this.m=void 0===n&&t instanceof b?t:t.minus(n)}return t.prototype.id=function(){return this.o},t.prototype.expression=function(){return this.m},t.prototype.op=function(){return this.v},t.prototype.strength=function(){return this.p},t.prototype.toString=function(){return this.m+" "+["<=",">=","="][this.v]+" 0 ("+this.p+")"},t}(),C=0,x=function(){function t(){this.S=d(),this.C=d(),this.M=d(),this.O=d(),this.T=[],this.I=new T,this.k=null,this.$=0}return t.prototype.createConstraint=function(t,i,n,s){void 0===s&&(s=g.required);var o=new E(t,i,n,s);return this.addConstraint(o),o},t.prototype.addConstraint=function(t){if(void 0!==this.S.find(t))throw Error("duplicate constraint");var i=this.D(t),n=i.row,s=i.tag,o=this.P(n,s);if(o.type()===S.Invalid&&n.allDummies()){if(!M(n.constant()))throw Error("unsatisfiable constraint");o=s.marker}if(o.type()===S.Invalid){if(!this.A(n))throw Error("unsatisfiable constraint")}else n.solveFor(o),this.j(o,n),this.C.insert(o,n);this.S.insert(t,s),this.H(this.I)},t.prototype.removeConstraint=function(t){var i=this.S.erase(t);if(void 0===i)throw Error("unknown constraint");this.V(t,i.second);var n=i.second.marker,s=this.C.erase(n);if(void 0===s){var o=this.K(n);if(o.type()===S.Invalid)throw Error("failed to find leaving row");(s=this.C.erase(o)).second.solveForEx(o,n),this.j(n,s.second)}this.H(this.I)},t.prototype.hasConstraint=function(t){return this.S.contains(t)},t.prototype.addEditVariable=function(t,i){if(void 0!==this.O.find(t))throw Error("duplicate edit variable");if((i=g.clip(i))===g.required)throw Error("bad required strength");var n=new b(t),s=new E(n,y.Eq,void 0,i);this.addConstraint(s);var o=this.S.find(s).second;this.O.insert(t,{tag:o,constraint:s,constant:0})},t.prototype.removeEditVariable=function(t){var i=this.O.erase(t);if(void 0===i)throw Error("unknown edit variable");this.removeConstraint(i.second.constraint)},t.prototype.hasEditVariable=function(t){return this.O.contains(t)},t.prototype.suggestValue=function(t,i){var n=this.O.find(t);if(void 0===n)throw Error("unknown edit variable");var s=this.C,o=n.second,r=i-o.constant;o.constant=i;var e=o.tag.marker,h=s.find(e);if(void 0!==h)return h.second.add(-r)<0&&this.T.push(e),void this.L();var l=o.tag.other;if(void 0!==(h=s.find(l)))return h.second.add(r)<0&&this.T.push(l),void this.L();for(var u=0,a=s.size();u<a;++u){var c=s.itemAt(u),d=c.second,v=d.coefficientFor(e);0!==v&&d.add(r*v)<0&&c.first.type()!==S.External&&this.T.push(c.first)}this.L()},t.prototype.updateVariables=function(){for(var t=this.M,i=this.C,n=0,s=t.size();n<s;++n){var o=t.itemAt(n),r=i.find(o.second);o.first.setValue(void 0!==r?r.second.constant():0)}},t.prototype.U=function(t){var i=this;return this.M.setDefault(t,(()=>i.B(S.External))).second},t.prototype.D=function(t){for(var i=t.expression(),n=new T(i.constant()),s=i.terms(),o=0,r=s.size();o<r;++o){var e=s.itemAt(o);if(!M(e.second)){var h=this.U(e.first),l=this.C.find(h);void 0!==l?n.insertRow(l.second,e.second):n.insertSymbol(h,e.second)}}var u=this.I,a=t.strength(),c={marker:O,other:O};switch(t.op()){case y.Le:case y.Ge:var d=t.op()===y.Le?1:-1,v=this.B(S.Slack);if(c.marker=v,n.insertSymbol(v,d),a<g.required){var f=this.B(S.Error);c.other=f,n.insertSymbol(f,-d),u.insertSymbol(f,a)}break;case y.Eq:if(a<g.required){var w=this.B(S.Error),p=this.B(S.Error);c.marker=w,c.other=p,n.insertSymbol(w,-1),n.insertSymbol(p,1),u.insertSymbol(w,a),u.insertSymbol(p,a)}else{var b=this.B(S.Dummy);c.marker=b,n.insertSymbol(b)}}return n.constant()<0&&n.reverseSign(),{row:n,tag:c}},t.prototype.P=(t,i)=>{for(var n=t.cells(),s=0,o=n.size();s<o;++s){var r=n.itemAt(s);if(r.first.type()===S.External)return r.first}var e=i.marker.type();return(e===S.Slack||e===S.Error)&&t.coefficientFor(i.marker)<0?i.marker:((e=i.other.type())===S.Slack||e===S.Error)&&t.coefficientFor(i.other)<0?i.other:O},t.prototype.A=function(t){var i=this.B(S.Slack);this.C.insert(i,t.copy()),this.k=t.copy(),this.H(this.k);var n=M(this.k.constant());this.k=null;var s=this.C.erase(i);if(void 0!==s){var o=s.second;if(o.isConstant())return n;var r=this.N(o);if(r.type()===S.Invalid)return 0;o.solveForEx(i,r),this.j(r,o),this.C.insert(r,o)}for(var e=this.C,h=0,l=e.size();h<l;++h)e.itemAt(h).second.removeSymbol(i);return this.I.removeSymbol(i),n},t.prototype.j=function(t,i){for(var n=this.C,s=0,o=n.size();s<o;++s){var r=n.itemAt(s);r.second.substitute(t,i),r.second.constant()<0&&r.first.type()!==S.External&&this.T.push(r.first)}this.I.substitute(t,i),this.k&&this.k.substitute(t,i)},t.prototype.H=function(t){for(;;){var i=this.R(t);if(i.type()===S.Invalid)return;var n=this.W(i);if(n.type()===S.Invalid)throw Error("the objective is unbounded");var s=this.C.erase(n).second;s.solveForEx(n,i),this.j(i,s),this.C.insert(i,s)}},t.prototype.L=function(){for(var t=this.C,i=this.T;0!==i.length;){var n=i.pop(),s=t.find(n);if(void 0!==s&&s.second.constant()<0){var o=this.Y(s.second);if(o.type()===S.Invalid)throw Error("dual optimize failed");var r=s.second;t.erase(n),r.solveForEx(n,o),this.j(o,r),t.insert(o,r)}}},t.prototype.R=t=>{for(var i=t.cells(),n=0,s=i.size();n<s;++n){var o=i.itemAt(n),r=o.first;if(o.second<0&&r.type()!==S.Dummy)return r}return O},t.prototype.Y=function(t){for(var i=Number.MAX_VALUE,n=O,s=t.cells(),o=0,r=s.size();o<r;++o){var e=s.itemAt(o),h=e.first,l=e.second;if(l>0&&h.type()!==S.Dummy){var u=this.I.coefficientFor(h)/l;u<i&&(i=u,n=h)}}return n},t.prototype.W=function(t){for(var i=Number.MAX_VALUE,n=O,s=this.C,o=0,r=s.size();o<r;++o){var e=s.itemAt(o),h=e.first;if(h.type()!==S.External){var l=e.second,u=l.coefficientFor(t);if(u<0){var a=-l.constant()/u;a<i&&(i=a,n=h)}}}return n},t.prototype.K=function(t){for(var i=Number.MAX_VALUE,n=i,s=i,o=O,r=o,e=o,h=o,l=this.C,u=0,a=l.size();u<a;++u){var c=l.itemAt(u),d=c.second,v=d.coefficientFor(t);if(0!==v){var f=c.first;if(f.type()===S.External)h=f;else if(v<0)(w=-d.constant()/v)<n&&(n=w,r=f);else{var w;(w=d.constant()/v)<s&&(s=w,e=f)}}}return r!==o?r:e!==o?e:h},t.prototype.V=function(t,i){i.marker.type()===S.Error&&this.X(i.marker,t.strength()),i.other.type()===S.Error&&this.X(i.other,t.strength())},t.prototype.X=function(t,i){var n=this.C.find(t);void 0!==n?this.I.insertRow(n.second,-i):this.I.insertSymbol(t,-i)},t.prototype.N=t=>{for(var i=t.cells(),n=0,s=i.size();n<s;++n){var o=i.itemAt(n),r=o.first.type();if(r===S.Slack||r===S.Error)return o.first}return O},t.prototype.B=function(t){return new z(t,this.$++)},t}();function M(t){return t<0?-t<1e-8:t<1e-8}(t=>{t[t.Invalid=0]="Invalid",t[t.External=1]="External",t[t.Slack=2]="Slack",t[t.Error=3]="Error",t[t.Dummy=4]="Dummy"})(S||(S={}));var z=function(){function t(t,i){this.o=i,this.q=t}return t.prototype.id=function(){return this.o},t.prototype.type=function(){return this.q},t}(),O=new z(S.Invalid,-1),T=function(){function t(t){void 0===t&&(t=0),this.F=d(),this.u=t}return t.prototype.cells=function(){return this.F},t.prototype.constant=function(){return this.u},t.prototype.isConstant=function(){return this.F.empty()},t.prototype.allDummies=function(){for(var t=this.F,i=0,n=t.size();i<n;++i)if(t.itemAt(i).first.type()!==S.Dummy)return 0;return 1},t.prototype.copy=function(){var i=new t(this.u);return i.F=this.F.copy(),i},t.prototype.add=function(t){return this.u+=t},t.prototype.insertSymbol=function(t,i){void 0===i&&(i=1),M(this.F.setDefault(t,(()=>0)).second+=i)&&this.F.erase(t)},t.prototype.insertRow=function(t,i){void 0===i&&(i=1),this.u+=t.u*i;for(var n=t.F,s=0,o=n.size();s<o;++s){var r=n.itemAt(s);this.insertSymbol(r.first,r.second*i)}},t.prototype.removeSymbol=function(t){this.F.erase(t)},t.prototype.reverseSign=function(){this.u=-this.u;for(var t=this.F,i=0,n=t.size();i<n;++i){var s=t.itemAt(i);s.second=-s.second}},t.prototype.solveFor=function(t){var i=this.F,n=-1/i.erase(t).second;this.u*=n;for(var s=0,o=i.size();s<o;++s)i.itemAt(s).second*=n},t.prototype.solveForEx=function(t,i){this.insertSymbol(t,-1),this.solveFor(i)},t.prototype.coefficientFor=function(t){var i=this.F.find(t);return void 0!==i?i.second:0},t.prototype.substitute=function(t,i){var n=this.F.erase(t);void 0!==n&&this.insertRow(i,n.second)},t}();const I=Symbol("xSymbol"),k=Symbol("ySymbol"),$=Symbol("widthSymbol"),D=Symbol("heightSymbol"),P=Symbol("addUIElementSymbol"),A=Symbol("removeUIElementSymbol"),j=Symbol("addConstraintSymbol"),H=Symbol("removeUIConstraintSymbol"),V=Symbol("addConstraintSymbol"),K=Symbol("removeConstraintSymbol"),L=Symbol("addVariableSymbol"),U=Symbol("removeVariableSymbol"),B=Symbol("suggestVariableSymbol"),N=Symbol("disableConstraintSymbol"),R=Symbol("enableConstraintSymbol"),W=Symbol("needsRecalculation"),Y=Symbol("flushTransformSymbol"),X=Symbol("clickSymbol");var q,F,G;function Q(t){return null!==t&&Object.values(q).some((i=>i===t))}function J(t){return null!=t?t:q.ALWAYS}(t=>{t[t.LANDSCAPE=0]="LANDSCAPE",t[t.PORTRAIT=1]="PORTRAIT",t[t.ALWAYS=2]="ALWAYS"})(q||(q={}));class Z{constructor(t,i){this.layer=t,this.layer[j](this,i)}destroy(){this.layer[H](this)}}function _(t){return null!==t&&Object.values(F).some((i=>i===t))}function tt(t){return null!=t?t:F.P0}function it(t){switch(t){case F.P0:return g.create(1e3,1e3,1e3);case F.P1:return g.create(100,0,0);case F.P2:return g.create(10,0,0);case F.P3:return g.create(0,100,0);case F.P4:return g.create(0,10,0);case F.P5:return g.create(0,0,100);case F.P6:return g.create(0,0,10);case F.P7:return g.create(0,0,1);default:return g.create(1e3,1e3,1e3)}}function nt(t){return null!==t&&Object.values(G).some((i=>i===t))}function st(t){return null!=t?t:G.EQUAL}function ot(t){switch(t){case G.EQUAL:return y.Eq;case G.LESS:return y.Le;case G.GREATER:return y.Ge;default:return y.Eq}}(t=>{t[t.P0=0]="P0",t[t.P1=1]="P1",t[t.P2=2]="P2",t[t.P3=3]="P3",t[t.P4=4]="P4",t[t.P5=5]="P5",t[t.P6=6]="P6",t[t.P7=7]="P7"})(F||(F={})),(t=>{t[t.EQUAL=2]="EQUAL",t[t.LESS=0]="LESS",t[t.GREATER=1]="GREATER"})(G||(G={}));class rt extends Z{constructor(t,i){var n;super(t.layer,new Set([t])),this.element=t,this.parameters={height:null!==(n=null==i?void 0:i.height)&&void 0!==n?n:100,power:tt(null==i?void 0:i.power),rule:st(null==i?void 0:i.rule),orientation:J(null==i?void 0:i.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){this.constraint=new E(new b(this.element[D]),ot(this.parameters.rule),this.parameters.height,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class et{constructor(){this.listeners=new Map}on(t,i,n,s=100){return this.addListener(t,i,n,s,0),this}once(t,i,n,s=100){return this.addListener(t,i,n,s,1),this}off(t,i,n){const s=this.listeners.get(t);if(!s)return this;if(!i)return this.listeners.delete(t),this;const o=s.filter((t=>t.callback!==i||void 0!==n&&t.context!==n));return o.length?this.listeners.set(t,o):this.listeners.delete(t),this}emit(t,...i){const n=this.listeners.get(t);if(!(null==n?void 0:n.length))return 0;for(const s of[...n])s.callback.apply(s.context,i),s.once&&this.off(t,s.callback,s.context);return 1}addListener(t,i,n,s,o){let r=this.listeners.get(t);if(r||(r=[],this.listeners.set(t,r)),r.some((t=>t.callback===i&&t.context===n)))throw Error("Event listener already exists");const e={callback:i,context:n,priority:s,once:o};let h=0;for(;h<r.length&&r[h].priority<=s;)h++;r.splice(h,0,e)}}const ht=new t,lt=new i;var ut,at;(t=>{t[t.HIDDEN=0]="HIDDEN",t[t.VISIBLE=1]="VISIBLE",t[t.INTERACTIVE=2]="INTERACTIVE"})(ut||(ut={}));const ct=.5;class dt{constructor(){this[at]=0,this.positionXInternal=0,this.positionYInternal=0,this.anchorXInternal=ct,this.anchorYInternal=ct,this.scaleXInternal=1,this.scaleYInternal=1,this.rotationInternal=0}get x(){return this.positionXInternal}get y(){return this.positionYInternal}get anchorX(){return this.anchorXInternal}get anchorY(){return this.anchorYInternal}get scaleX(){return this.scaleXInternal}get scaleY(){return this.scaleYInternal}get angle(){return n.radToDeg(this.rotationInternal)}get rotation(){return this.rotationInternal}set x(t){this.positionXInternal=t,this[W]=1}set y(t){this.positionYInternal=t,this[W]=1}set anchorX(t){this.anchorXInternal=t,this[W]=1}set anchorY(t){this.anchorYInternal=t,this[W]=1}set scaleX(t){this.scaleXInternal=t,this[W]=1}set scaleY(t){this.scaleYInternal=t,this[W]=1}set angle(t){this.rotationInternal=n.degToRad(t),this[W]=1}set rotation(t){this.rotationInternal=t,this[W]=1}reset(){this.positionXInternal=0,this.positionYInternal=0,this.anchorXInternal=ct,this.anchorYInternal=ct,this.scaleXInternal=1,this.scaleYInternal=1,this.rotationInternal=0,this[W]=1}}var vt,ft,wt,pt,bt,mt,yt,gt,St,Et;at=W,(t=>{t.CLICK="click"})(mt||(mt={}));class Ct extends et{constructor(t,i,n,s,o,r){super(),this.layer=t,this.object=i,this.micro=new dt,this[vt]=new w("x"),this[ft]=new w("y"),this[wt]=new w("width"),this[pt]=new w("height"),this[bt]=0,this.behaviorInternal=ut.VISIBLE,this.layer[P](this,this.object),this.layer[L](this,this[I],it(F.P7)),this.layer[L](this,this[k],it(F.P7)),this.layer[L](this,this[$],it(F.P5)),this.layer[L](this,this[D],it(F.P5)),this[I].setValue(n),this[k].setValue(s),this[$].setValue(o),this[D].setValue(r),this.layer[B](this,this[I],n),this.layer[B](this,this[k],s),this.layer[B](this,this[$],o),this.layer[B](this,this[D],r)}get x(){return this[I].value()}get y(){return this[k].value()}get width(){return this[$].value()}get height(){return this[D].value()}get zIndex(){return this.object.position.z}get behavior(){return this.behaviorInternal}set x(t){this.layer[B](this,this[I],t)}set y(t){this.layer[B](this,this[k],t)}set width(t){this.layer[B](this,this[$],t)}set height(t){this.layer[B](this,this[D],t)}set zIndex(t){this.object.position.z=t}set behavior(t){this.behaviorInternal=t,this.object.visible=t!==ut.HIDDEN}destroy(){this.layer[U](this,this[I]),this.layer[U](this,this[k]),this.layer[U](this,this[$]),this.layer[U](this,this[D]),this.layer[A](this)}[(vt=I,ft=k,wt=$,pt=D,bt=W,Y)](){(this[W]||this.micro[W])&&(((t,i,n,s,o,r)=>{const e=this.y+r*i.anchorY,h=i.y;t.position.x=this.x+o*i.anchorX+i.x,t.position.y=e+h,t.scale.x=i.scaleX*o,t.scale.y=i.scaleY*r,t.rotation.z=i.rotation;const l=i.anchorY*i.scaleY*r;t.position.x-=i.anchorX*i.scaleX*o,t.position.y-=l})(this.object,this.micro,0,0,this.width,this.height),this[W]=0,this.micro[W]=0)}[X](t,i){return this.behavior!==ut.INTERACTIVE?0:(this[Y](),n=this.x,s=this.y,o=this.width,r=this.height,ht.set(t,i),lt.min.set(n,s),lt.max.set(o,r).add(lt.min),lt.containsPoint(ht)?(this.emit(mt.CLICK,this),1):0);var n,s,o,r}}class xt{constructor(){this.behavior=ut.VISIBLE,this[yt]=new w,this[gt]=new w,this[St]=new w,this[Et]=new w,this.scene=new s,this.camera=new o,this.solver=new x,this.elements=new Map,this.constraints=new Map,this.orientationPrivate=q.PORTRAIT,this.needsRecalculation=0}get orientation(){return this.orientationPrivate}destroy(){this.solver=void 0;for(const t of this.constraints.keys())t.destroy();for(const t of this.elements.keys())t.destroy()}[(yt=I,gt=k,St=$,Et=D,P)](t,i){if(this.elements.has(t))throw Error("Element already added");this.elements.set(t,{object:i,variables:new Map,constraints:new Set}),this.scene.add(i)}[A](t){const i=this.elements.get(t);if(void 0===i)throw Error("Element not found");if(i.variables.size>0)throw Error("Variables should be removed before removing element");if(i.constraints.size>0)throw Error("Constraints should be removed before removing element");this.elements.delete(t),this.scene.remove(i.object)}[j](t,i){if(this.constraints.has(t))throw Error("Constraint already added");for(const n of i){const i=this.elements.get(n);if(void 0===i)throw Error("Element not found");if(i.constraints.has(t))throw Error("Something went wrong");i.constraints.add(t)}this.constraints.set(t,{elements:i,variables:new Map,constraints:new Set})}[H](t){const i=this.constraints.get(t);if(void 0===i)throw Error("Constraint not found");if(i.variables.size>0)throw Error("Variables should be removed before removing constraint");if(i.constraints.size>0)throw Error("Constraints should be removed before removing constraint");for(const n of i.elements){const i=this.elements.get(n);if(void 0===i)throw Error("Element not found");if(!i.constraints.has(t))throw Error("Something went wrong");i.constraints.delete(t)}this.constraints.delete(t)}[V](t,i){var n;const s=this.constraints.get(t);if(void 0===s)throw Error("Before adding constraint you need to add it's owner");if(s.constraints.has(i))throw Error("Constraint already exists");s.constraints.add(i),null===(n=this.solver)||void 0===n||n.addConstraint(i),this.needsRecalculation=1}[K](t,i){var n;const s=this.constraints.get(t);if(void 0===s)throw Error("Before removing constraint you need to add it's owner");if(!s.constraints.has(i))throw Error("Constraint not found");s.constraints.delete(i),null===(n=this.solver)||void 0===n||n.removeConstraint(i),this.needsRecalculation=1}[L](t,i,n){var s;const o=t instanceof Ct?this.elements.get(t):this.constraints.get(t);if(void 0===o)throw Error("Before adding variable you need to add it's owner");if(o.variables.has(i))throw Error("Variable already exists");o.variables.set(i,{strength:n,suggestedValue:i.value()}),null===(s=this.solver)||void 0===s||s.addEditVariable(i,n)}[U](t,i){var n;const s=t instanceof Ct?this.elements.get(t):this.constraints.get(t);if(void 0===s)throw Error("Before removing variable you need to add it's owner");if(!s.variables.has(i))throw Error("Variable does not exist");s.variables.delete(i),null===(n=this.solver)||void 0===n||n.removeEditVariable(i)}[B](t,i,n){var s;const o=t instanceof Ct?this.elements.get(t):this.constraints.get(t);if(void 0===o)throw Error("Before suggesting variable you need to add it's owner");const r=o.variables.get(i);if(!r)throw Error("Variable does not exist");r.suggestedValue!==n&&(r.suggestedValue=n,null===(s=this.solver)||void 0===s||s.suggestValue(i,n),this.needsRecalculation=1)}render(t){var i;if(this.behavior!==ut.HIDDEN){if(this.needsRecalculation){this.needsRecalculation=0,null===(i=this.solver)||void 0===i||i.updateVariables();for(const t of this.elements.keys())t[W]=1}for(const t of this.elements.keys())t[W]=1;for(const t of this.elements.keys())t[Y]();t.render(this.scene,this.camera)}}clickInternal(t,i){if(this.behavior!==ut.INTERACTIVE)return;const n=[...this.elements.keys()].filter((t=>t.behavior===ut.INTERACTIVE)).sort(((t,i)=>t.zIndex-i.zIndex));for(const s of n)if(s[X](t,i))break}resizeInternal(t,i){this.applyCameraSize(t,i),this.rebuildLayerConstraints(t,i),this.updateOrientation(t,i),this.needsRecalculation=1}applyCameraSize(t,i){this.camera.near=-1e3,this.camera.far=0,this.camera.bottom=0,this.camera.left=0,this.camera.right=t,this.camera.top=i,this.camera.updateProjectionMatrix()}rebuildLayerConstraints(t,i){var n,s,o,r,e,h,l,u;this.constraintX&&(null===(n=this.solver)||void 0===n||n.removeConstraint(this.constraintX),this.constraintX=void 0),this.constraintY&&(null===(s=this.solver)||void 0===s||s.removeConstraint(this.constraintY),this.constraintY=void 0),this.constraintW&&(null===(o=this.solver)||void 0===o||o.removeConstraint(this.constraintW),this.constraintW=void 0),this.constraintH&&(null===(r=this.solver)||void 0===r||r.removeConstraint(this.constraintH),this.constraintH=void 0),this.constraintX=new E(new b(this[I]),y.Eq,0,g.required),this.constraintY=new E(new b(this[k]),y.Eq,0,g.required),this.constraintW=new E(new b(this[$]),y.Eq,t,g.required),this.constraintH=new E(new b(this[D]),y.Eq,i,g.required),null===(e=this.solver)||void 0===e||e.addConstraint(this.constraintX),null===(h=this.solver)||void 0===h||h.addConstraint(this.constraintY),null===(l=this.solver)||void 0===l||l.addConstraint(this.constraintW),null===(u=this.solver)||void 0===u||u.addConstraint(this.constraintH)}updateOrientation(t,i){const n=this.orientationPrivate;if(this.orientationPrivate=t>i?q.LANDSCAPE:q.PORTRAIT,n!==this.orientationPrivate){this.solver=void 0;for(const t of this.constraints.keys())t[R](this.orientationPrivate);for(const t of this.constraints.keys())t[N](this.orientationPrivate);this.solver=new x;const t=[...this.elements.values(),...this.constraints.values()];for(const i of t)for(const[t,n]of i.variables.entries())this.solver.addEditVariable(t,n.strength),this.solver.suggestValue(t,n.suggestedValue);this.constraintX&&this.solver.addConstraint(this.constraintX),this.constraintY&&this.solver.addConstraint(this.constraintY),this.constraintW&&this.solver.addConstraint(this.constraintW),this.constraintH&&this.solver.addConstraint(this.constraintH);for(const t of this.constraints.values())for(const i of t.constraints.values())this.solver.addConstraint(i)}}}function Mt(t,i){if((t instanceof xt?t:t.layer)!==i.layer)throw Error(`Elements must be on the same layer - element "${i.constructor.name}" cannot interact with elements from a different layer`)}class zt extends Z{constructor(t,i,n){var s,o,r;Mt(t,i),super(i.layer,new Set(t instanceof Ct?[t,i]:[i])),this.elementOne=t,this.elementTwo=i,this.parameters={anchorOne:null!==(s=null==n?void 0:n.anchorOne)&&void 0!==s?s:.5,anchorTwo:null!==(o=null==n?void 0:n.anchorTwo)&&void 0!==o?o:.5,distance:null!==(r=null==n?void 0:n.distance)&&void 0!==r?r:0,power:tt(null==n?void 0:n.power),rule:st(null==n?void 0:n.rule),orientation:J(null==n?void 0:n.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){const t=new b(this.elementOne[I]).plus(new b(this.elementOne[$]).multiply(this.parameters.anchorOne)),i=new b(this.elementTwo[I]).plus(new b(this.elementTwo[$]).multiply(this.parameters.anchorTwo));this.constraint=new E(i.minus(t),ot(this.parameters.rule),this.parameters.distance,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class Ot extends Z{constructor(t,i,n){var s;Mt(t,i),super(i.layer,new Set(t instanceof Ct?[t,i]:[i])),this.elementOne=t,this.elementTwo=i,this.parameters={proportion:null!==(s=null==n?void 0:n.proportion)&&void 0!==s?s:1,power:tt(null==n?void 0:n.power),rule:st(null==n?void 0:n.rule),orientation:J(null==n?void 0:n.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){const t=new b(this.elementOne[$]).multiply(this.parameters.proportion),i=new b(this.elementTwo[$]);this.constraint=new E(t.minus(i),ot(this.parameters.rule),0,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class Tt extends Z{constructor(t,i,n){var s,o,r;Mt(t,i),super(i.layer,new Set(t instanceof Ct?[t,i]:[i])),this.elementOne=t,this.elementTwo=i,this.parameters={anchorOne:null!==(s=null==n?void 0:n.anchorOne)&&void 0!==s?s:.5,anchorTwo:null!==(o=null==n?void 0:n.anchorTwo)&&void 0!==o?o:.5,distance:null!==(r=null==n?void 0:n.distance)&&void 0!==r?r:0,power:tt(null==n?void 0:n.power),rule:st(null==n?void 0:n.rule),orientation:J(null==n?void 0:n.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){const t=new b(this.elementOne[k]).plus(new b(this.elementOne[D]).multiply(this.parameters.anchorOne)),i=new b(this.elementTwo[k]).plus(new b(this.elementTwo[D]).multiply(this.parameters.anchorTwo));this.constraint=new E(i.minus(t),ot(this.parameters.rule),this.parameters.distance,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class It extends Z{constructor(t,i,n){var s;Mt(t,i),super(i.layer,new Set(t instanceof Ct?[t,i]:[i])),this.elementOne=t,this.elementTwo=i,this.parameters={proportion:null!==(s=null==n?void 0:n.proportion)&&void 0!==s?s:1,power:tt(null==n?void 0:n.power),rule:st(null==n?void 0:n.rule),orientation:J(null==n?void 0:n.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){const t=new b(this.elementOne[D]).multiply(this.parameters.proportion),i=new b(this.elementTwo[D]);this.constraint=new E(t.minus(i),ot(this.parameters.rule),0,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class kt extends Z{constructor(t,i){var n;super(t.layer,new Set([t])),this.element=t,this.parameters={width:null!==(n=null==i?void 0:i.width)&&void 0!==n?n:100,power:tt(null==i?void 0:i.power),rule:st(null==i?void 0:i.rule),orientation:J(null==i?void 0:i.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){this.constraint=new E(new b(this.element[$]),ot(this.parameters.rule),this.parameters.width,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class $t{static size2D(t){return{width:new kt(t.element,{width:t.width,power:t.powerHorizontal,rule:t.ruleHorizontal,orientation:t.orientationHorizontal}),height:new rt(t.element,{height:t.height,power:t.powerVertical,rule:t.ruleVertical,orientation:t.orientationVertical})}}static distance2D(t){return{horizontal:new zt(t.elementOne,t.elementTwo,{anchorOne:t.anchorHorizontalOne,anchorTwo:t.anchorHorizontalTwo,distance:t.distanceHorizontal,power:t.powerHorizontal,rule:t.ruleHorizontal,orientation:t.orientationHorizontal}),vertical:new Tt(t.elementOne,t.elementTwo,{anchorOne:t.anchorVerticalOne,anchorTwo:t.anchorVerticalTwo,distance:t.distanceVertical,power:t.powerVertical,rule:t.ruleVertical,orientation:t.orientationVertical})}}static proportional2D(t){return{horizontal:new Ot(t.elementOne,t.elementTwo,{proportion:t.proportionHorizontal,power:t.powerHorizontal,rule:t.ruleHorizontal,orientation:t.orientationHorizontal}),vertical:new It(t.elementOne,t.elementTwo,{proportion:t.proportionVertical,power:t.powerVertical,rule:t.ruleVertical,orientation:t.orientationVertical})}}}class Dt extends Z{constructor(t,i){var n;super(t.layer,new Set([t])),this.element=t,this.parameters={aspect:null!==(n=null==i?void 0:i.aspect)&&void 0!==n?n:this.element.width/this.element.height,power:tt(null==i?void 0:i.power),rule:st(null==i?void 0:i.rule),orientation:J(null==i?void 0:i.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){const t=new b(this.element[$]).plus(new b(this.element[D]).multiply(-this.parameters.aspect));this.constraint=new E(t,ot(this.parameters.rule),0,it(this.parameters.power)),this.layer[V](this,this.constraint)}destroyConstraints(){this.constraint&&(this.layer[K](this,this.constraint),this.constraint=void 0)}}class Pt extends Z{constructor(t,i,n){var s,o,r;Mt(t,i),super(i.layer,new Set(t instanceof Ct?[t,i]:[i])),this.elementOne=t,this.elementTwo=i,this.parameters={isStrict:null!==(s=null==n?void 0:n.isStrict)&&void 0!==s?s:1,horizontalAnchor:null!==(o=null==n?void 0:n.horizontalAnchor)&&void 0!==o?o:.5,verticalAnchor:null!==(r=null==n?void 0:n.verticalAnchor)&&void 0!==r?r:.5,orientation:J(null==n?void 0:n.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){this.constraintX=new E(new b(this.elementOne[I]).plus(new b(this.elementOne[$]).multiply(this.parameters.horizontalAnchor)),y.Eq,new b(this.elementTwo[I]).plus(new b(this.elementTwo[$]).multiply(this.parameters.horizontalAnchor))),this.constraintY=new E(new b(this.elementOne[k]).plus(new b(this.elementOne[D]).multiply(this.parameters.verticalAnchor)),y.Eq,new b(this.elementTwo[k]).plus(new b(this.elementTwo[D]).multiply(this.parameters.verticalAnchor))),this.constraintW=new E(new b(this.elementOne[$]),y.Le,new b(this.elementTwo[$])),this.constraintH=new E(new b(this.elementOne[D]),y.Le,new b(this.elementTwo[D])),this.layer[V](this,this.constraintX),this.layer[V](this,this.constraintY),this.layer[V](this,this.constraintW),this.layer[V](this,this.constraintH),this.parameters.isStrict||(this.constraintStrict=new E(new b(this.elementOne[D]),y.Eq,new b(this.elementTwo[D]),g.strong),this.layer[V](this,this.constraintStrict))}destroyConstraints(){this.constraintX&&(this.layer[K](this,this.constraintX),this.constraintX=void 0),this.constraintY&&(this.layer[K](this,this.constraintY),this.constraintY=void 0),this.constraintW&&(this.layer[K](this,this.constraintW),this.constraintW=void 0),this.constraintH&&(this.layer[K](this,this.constraintH),this.constraintH=void 0),this.constraintStrict&&(this.layer[K](this,this.constraintStrict),this.constraintStrict=void 0)}}function At(t){return null!==t&&"object"==typeof t&&("x"in t&&"number"==typeof t.x||"y"in t&&"number"==typeof t.y)}function jt(t){return null!==t&&"object"==typeof t&&("x"in t&&_(t.x)||"y"in t&&_(t.y))}function Ht(t){return null!==t&&"object"==typeof t&&("x"in t&&nt(t.x)||"y"in t&&nt(t.y))}function Vt(t){return null!==t&&"object"==typeof t&&"elementOne"in t&&"elementTwo"in t&&(t.elementOne instanceof Ct||t.elementOne instanceof xt)&&t.elementTwo instanceof Ct}function Kt(t){return Vt(t)&&"distance"in t&&At(t.distance)&&(!("anchorOne"in t)||"anchorOne"in t&&At(t.anchorOne))&&(!("anchorTwo"in t)||"anchorTwo"in t&&At(t.anchorTwo))&&(!("power"in t)||jt(t.power))&&(!("rule"in t)||Ht(t.rule))&&(!("orientation"in t)||Q(t.orientation))}function Lt(t){return Vt(t)&&"proportion"in t&&At(t.proportion)&&(!("power"in t)||jt(t.power))&&(!("rule"in t)||Ht(t.rule))&&(!("orientation"in t)||Q(t.orientation))}function Ut(t){return Vt(t)&&"isStrict"in t&&"boolean"==typeof t.isStrict&&(!("anchor"in t)||"anchor"in t&&At(t.anchor))}function Bt(t){return null!==t&&"object"==typeof t&&"element"in t&&t.element instanceof Ct&&(!("power"in t)||_(t.power))&&(!("rule"in t)||nt(t.rule))}function Nt(t){return Bt(t)&&"height"in t&&"number"==typeof t.height}function Rt(t){return Bt(t)&&"keepAspect"in t&&"boolean"==typeof t.keepAspect}function Wt(t){return Bt(t)&&"keepSize"in t&&"boolean"==typeof t.keepSize}class Yt{static fromDescription(t){const i=t instanceof Map?t.entries():Object.entries(t),n=new Map;for(const[t,o]of i){if(n.has(t))throw Error(`Duplicate constraint key "${t}" - each constraint must have a unique identifier`);if(Bt(s=o)&&"width"in s&&"number"==typeof s.width)Yt.buildWidthConstraint(t,o,n);else if(Nt(o))Yt.buildHeightConstraint(t,o,n);else if(Rt(o))Yt.buildKeepAspectConstraint(t,o,n);else if(Wt(o))Yt.buildKeepSizeConstraint(t,o,n);else if(Kt(o))Yt.buildDistanceConstraint(t,o,n);else if(Lt(o))Yt.buildProportionalConstraint(t,o,n);else{if(!Ut(o))throw Error(`Invalid constraint type for "${t}". Expected one of: Width, Height, KeepAspect, KeepSize, Distance, Proportional, or Cover constraint`);Yt.buildCoverConstraint(t,o,n)}}var s;return Object.fromEntries(n)}static buildWidthConstraint(t,i,n){n.set(t,new kt(i.element,{width:i.width,power:i.power,rule:i.rule,orientation:i.orientation}))}static buildHeightConstraint(t,i,n){n.set(t,new rt(i.element,{height:i.height,power:i.power,rule:i.rule,orientation:i.orientation}))}static buildKeepAspectConstraint(t,i,n){n.set(t,new Dt(i.element,{power:i.power,rule:i.rule,orientation:i.orientation}))}static buildKeepSizeConstraint(t,i,n){const s=t.replace(/(KeepSize|Keep)$/,"")+"KeepWidth",o=t.replace(/(KeepSize|Keep)$/,"")+"KeepHeight";n.set(s,new kt(i.element,{power:i.power,rule:i.rule,orientation:i.orientation})),n.set(o,new rt(i.element,{power:i.power,rule:i.rule,orientation:i.orientation}))}static buildDistanceConstraint(t,i,n){var s,o,r,e,h,l,u,a;if("number"==typeof i.distance.x){const h=t.replace(/(HorizontalDistance|Distance)$/,"")+"HorizontalDistance";n.set(h,new zt(i.elementOne,i.elementTwo,{distance:i.distance.x,anchorOne:null===(s=i.anchorOne)||void 0===s?void 0:s.x,anchorTwo:null===(o=i.anchorTwo)||void 0===o?void 0:o.x,power:null===(r=i.power)||void 0===r?void 0:r.x,rule:null===(e=i.rule)||void 0===e?void 0:e.x,orientation:i.orientation}))}if("number"==typeof i.distance.y){const s=t.replace(/(VerticalDistance|Distance)$/,"")+"VerticalDistance";n.set(s,new Tt(i.elementOne,i.elementTwo,{distance:i.distance.y,anchorOne:null===(h=i.anchorOne)||void 0===h?void 0:h.y,anchorTwo:null===(l=i.anchorTwo)||void 0===l?void 0:l.y,power:null===(u=i.power)||void 0===u?void 0:u.y,rule:null===(a=i.rule)||void 0===a?void 0:a.y,orientation:i.orientation}))}}static buildProportionalConstraint(t,i,n){var s,o,r,e;if("number"==typeof i.proportion.x){const r=t.replace(/(HorizontalProportional|HorizontalProportion|Proportional|Proportion)$/,"")+"HorizontalProportion";n.set(r,new Ot(i.elementOne,i.elementTwo,{proportion:i.proportion.x,power:null===(s=i.power)||void 0===s?void 0:s.x,rule:null===(o=i.rule)||void 0===o?void 0:o.x,orientation:i.orientation}))}if("number"==typeof i.proportion.y){const s=t.replace(/(VerticalProportional|VerticalProportion|Proportional|Proportion)$/,"")+"VerticalProportion";n.set(s,new It(i.elementOne,i.elementTwo,{proportion:i.proportion.y,power:null===(r=i.power)||void 0===r?void 0:r.y,rule:null===(e=i.rule)||void 0===e?void 0:e.y,orientation:i.orientation}))}}static buildCoverConstraint(t,i,n){var s,o;n.set(t,new Pt(i.elementOne,i.elementTwo,{isStrict:i.isStrict,horizontalAnchor:null===(s=i.anchor)||void 0===s?void 0:s.x,verticalAnchor:null===(o=i.anchor)||void 0===o?void 0:o.y}))}}class Xt extends Ct{constructor(t,i=100,n=100){super(t,new r,0,0,i,n),this[Y]()}}const qt=new e(1,1).translate(.5,.5,0);class Ft extends Ct{constructor(t,i){var n,s;const o=null===(n=i.image)||void 0===n?void 0:n.width,r=null===(s=i.image)||void 0===s?void 0:s.height;((t,i,n)=>{if(t<=0||i<=0)throw Error(null!=n?n:`Invalid dimensions: width (${t}) and height (${i}) must both be positive numbers greater than 0`)})(o,r,`Invalid image dimensions - texture "${i.name||"unnamed"}" has invalid width (${o}) or height (${r}). Image dimensions must be non-zero positive numbers.`);const e=new h({map:i,transparent:1,side:l});super(t,new u(qt,e),0,0,o,r),this.material=e,this[Y]()}destroy(){this.material.dispose(),super.destroy()}}function Gt(t,i){var n,s,o,r,e,h,l,u,a,c,d,v,f,w,p,b,m,y,g,S,E,C,x,M,z,O,T,I;const k=Math.max(null!==(s=null!==(n=null==t?void 0:t.fontSize)&&void 0!==n?n:null==i?void 0:i.fontSize)&&void 0!==s?s:16,1),$=null!==(r=null!==(o=null==t?void 0:t.lineHeight)&&void 0!==o?o:null==i?void 0:i.lineHeight)&&void 0!==r?r:1.2*k,D=Math.max(null!==(h=null!==(e=null==t?void 0:t.shadowBlur)&&void 0!==e?e:null==i?void 0:i.shadowBlur)&&void 0!==h?h:0,0),P=Math.max(null!==(u=null!==(l=null==t?void 0:t.strokeWidth)&&void 0!==l?l:null==i?void 0:i.strokeWidth)&&void 0!==u?u:0,0);return{color:null!==(c=null!==(a=null==t?void 0:t.color)&&void 0!==a?a:null==i?void 0:i.color)&&void 0!==c?c:"#000000",fontFamily:null!==(v=null!==(d=null==t?void 0:t.fontFamily)&&void 0!==d?d:null==i?void 0:i.fontFamily)&&void 0!==v?v:"Arial",fontSize:k,fontStyle:null!==(w=null!==(f=null==t?void 0:t.fontStyle)&&void 0!==f?f:null==i?void 0:i.fontStyle)&&void 0!==w?w:"normal",fontWeight:null!==(b=null!==(p=null==t?void 0:t.fontWeight)&&void 0!==p?p:null==i?void 0:i.fontWeight)&&void 0!==b?b:"normal",lineHeight:$,enableShadow:null!==(y=null!==(m=null==t?void 0:t.enableShadow)&&void 0!==m?m:null==i?void 0:i.enableShadow)&&void 0!==y?y:0,shadowOffsetX:null!==(S=null!==(g=null==t?void 0:t.shadowOffsetX)&&void 0!==g?g:null==i?void 0:i.shadowOffsetX)&&void 0!==S?S:0,shadowOffsetY:null!==(C=null!==(E=null==t?void 0:t.shadowOffsetY)&&void 0!==E?E:null==i?void 0:i.shadowOffsetY)&&void 0!==C?C:0,shadowBlur:D,shadowColor:null!==(M=null!==(x=null==t?void 0:t.shadowColor)&&void 0!==x?x:null==i?void 0:i.shadowColor)&&void 0!==M?M:"transparent",enableStroke:null!==(O=null!==(z=null==t?void 0:t.enableStroke)&&void 0!==z?z:null==i?void 0:i.enableStroke)&&void 0!==O?O:0,strokeColor:null!==(I=null!==(T=null==t?void 0:t.strokeColor)&&void 0!==T?T:null==i?void 0:i.strokeColor)&&void 0!==I?I:"transparent",strokeWidth:P}}function Qt(t){return t.match(/\S+|\s|\n/g)||[]}function Jt(t,i,n){if(t.font=`${n.fontStyle} ${n.fontWeight} ${n.fontSize}px ${n.fontFamily}`,"\n"===i)return{width:0,height:n.lineHeight,baseline:0,lineHeight:n.lineHeight};const s=t.measureText(i),o=s.width,r=Math.ceil(s.actualBoundingBoxAscent+s.actualBoundingBoxDescent);return{width:Math.ceil(o),height:r,baseline:s.actualBoundingBoxDescent,lineHeight:n.lineHeight}}function Zt(t,i,n,s,o){o.font=`${s.fontStyle} ${s.fontWeight} ${s.fontSize}px ${s.fontFamily}`,s.enableShadow&&(o.shadowOffsetX=s.shadowOffsetX,o.shadowOffsetY=s.shadowOffsetY,o.shadowBlur=s.shadowBlur,o.shadowColor=s.shadowColor),s.enableStroke&&(o.strokeStyle=s.strokeColor,o.lineWidth=s.strokeWidth,o.strokeText(n,t,i)),o.fillStyle=s.color,o.fillText(n,t,i)}class _t extends Ct{constructor(t,i,n={}){var s;const o=document.createElement("canvas"),r=o.getContext("2d");if(!r)throw Error("Failed to create canvas context");const e=[];for(const t of i){const i="string"==typeof t,s=i?t:t.text,o=Gt(i?void 0:t.style,n.defaultStyle);for(const t of Qt(s)){const i=Jt(r,t,o);e.push({text:t,style:o,metrics:i})}}const c=((t,i)=>{const n=[];let s=[],o=0,r=0,e=0,h=0;for(const l of i)"\n"!==l.text?o+l.metrics.width<=t||0===s.length?(s.push(l),o+=l.metrics.width,r=Math.max(r,l.metrics.height),e=Math.max(e,l.metrics.baseline),h=Math.max(h,l.metrics.lineHeight)):(n.push({chunks:s,width:o,height:r,baseline:e,lineHeight:h}),s=[l],o=l.metrics.width,r=l.metrics.height,e=l.metrics.baseline,h=l.metrics.lineHeight):(s.length>0&&n.push({chunks:s,width:o,height:r,baseline:e,lineHeight:h}),s=[],o=0,r=0,e=0,h=0);return s.length>0&&n.push({chunks:s,width:o,height:r,baseline:e,lineHeight:h}),n})(null!==(s=n.maxWidth)&&void 0!==s?s:1024,e),d=(t=>{if(0===t.length)return{width:0,height:0};const i=Math.max(...t.map((t=>t.width)));let n=0;for(let i=0;i<t.length;i++){const s=t[i];n+=0===i?s.height:s.lineHeight,i===t.length-1&&(n+=s.baseline)}return{width:i,height:n}})(c),v=(t=>{var i,n,s,o;return"number"==typeof t?{left:t,right:t,top:t,bottom:t}:{left:Math.max(null!==(i=null==t?void 0:t.left)&&void 0!==i?i:0,0),right:Math.max(null!==(n=null==t?void 0:t.right)&&void 0!==n?n:0,0),top:Math.max(null!==(s=null==t?void 0:t.top)&&void 0!==s?s:0,0),bottom:Math.max(null!==(o=null==t?void 0:t.bottom)&&void 0!==o?o:0,0)}})(n.padding);o.width=d.width+v.left+v.right,o.height=d.height+v.top+v.bottom;const f=new a(o),w=new h({map:f,transparent:1,side:l});super(t,new u(qt,w),0,0,d.width,d.height),this.lastSuggestedAspect=0,this.texture=f,this.material=w,this.canvas=o,this.context=r,this.textBlockSize=d,this.padding=v,((t,i,n,s)=>{let o=this.padding.top;for(let t=0;t<n.length;t++){const r=n[t];let e=i;o+=0===t?r.height:r.lineHeight;for(const t of r.chunks)Zt(e,o,t.text,t.style,s),e+=t.metrics.width}})(0,this.padding.left,c,this.context),this.texture.needsUpdate=1,this[Y]()}destroy(){this.material.dispose(),this.texture.dispose(),this.canvas.remove(),super.destroy()}[Y](){super[Y]();const t=this.width/this.height;this.lastSuggestedAspect!==t&&(this.lastSuggestedAspect=t,this.layer[B](this,this[D],this.width/((this.textBlockSize.width+this.padding.left+this.padding.right)/(this.textBlockSize.height+this.padding.top+this.padding.bottom))))}}function ti(t){return null!==t&&"object"==typeof t&&"text"in t&&"string"==typeof t.text}function ii(t){return null!==t&&"object"==typeof t&&"spans"in t&&Array.isArray(t.spans)&&t.spans.every((t=>"string"==typeof t||(t=>null!==t&&"object"==typeof t&&"text"in t&&"string"==typeof t.text)(t)))}function ni(t){return!(null===t||"object"!=typeof t||"width"in t&&"number"!=typeof t.width||"height"in t&&"number"!=typeof t.height)}class si{static fromDescription(t,i){const n=i instanceof Map?i.entries():Object.entries(i),s=new Map;for(const[i,r]of n){if(s.has(i))throw Error(`Duplicate element key "${i}" - each UI element must have a unique identifier`);let n;if(r instanceof c)n=new Ft(t,r);else if(null!==(o=r)&&"object"==typeof o&&"texture"in o&&o.texture instanceof c)n=new Ft(t,r.texture);else if("string"==typeof r)n=new _t(t,[r]);else if(ti(r))n=new _t(t,[r.text],{defaultStyle:r.style});else if(ii(r))n=new _t(t,r.spans,{defaultStyle:r.defaultStyle});else{if(!ni(r))throw Error(`Invalid UI element type for "${i}". Expected one of: Texture, UIImage, String, UITextDescription, or UITextEnhancedDescription`);n=new Xt(t,r.width,r.height)}s.set(i,n)}var o;return Object.fromEntries(s)}}class oi{static buildHorizontal(t){const i=[],n=[],s=[];for(let o=0;o<t.elements.length-1;o++){const r=t.elements[o],e=t.elements[o+1];i.push(new zt(r,e,{anchorOne:1,anchorTwo:0,distance:t.offset,power:t.power})),n.push(new Ot(r,e,{power:t.power})),0!=t.keepAlignment&&s.push(new Tt(r,e,{power:t.power,anchorOne:0,anchorTwo:0}))}return{dummy:0!=t.createDummy?oi.createDummy(t.elements[0],t.elements[t.elements.length-1]):void 0,distanceConstraints:i,proportionConstraints:n,centerConstraints:s}}static buildVertical(t){const i=[],n=[],s=[];for(let o=0;o<t.elements.length-1;o++){const r=t.elements[o],e=t.elements[o+1];i.push(new Tt(r,e,{anchorOne:1,anchorTwo:0,distance:t.offset,power:t.power})),n.push(new It(r,e,{power:t.power})),0!=t.keepAlignment&&s.push(new zt(r,e,{power:t.power}))}return{dummy:0!=t.createDummy?oi.createDummy(t.elements[0],t.elements[t.elements.length-1]):void 0,distanceConstraints:i,proportionConstraints:n,centerConstraints:s}}static createDummy(t,i){const n=new Xt(i.layer);return new zt(n,t,{distance:0,anchorOne:0,anchorTwo:0}),new Tt(n,t,{distance:0,anchorOne:0,anchorTwo:0}),new zt(n,i,{distance:0,anchorOne:1,anchorTwo:1}),new Tt(n,i,{distance:0,anchorOne:1,anchorTwo:1}),n}}class ri extends Z{constructor(t,i,n){var s,o,r;super(i.layer,new Set(t instanceof Ct?[t,i]:[i])),this.elementOne=t,this.elementTwo=i,Mt(t,i),this.parameters={isStrict:null!==(s=null==n?void 0:n.isStrict)&&void 0!==s?s:1,horizontalAnchor:null!==(o=null==n?void 0:n.horizontalAnchor)&&void 0!==o?o:.5,verticalAnchor:null!==(r=null==n?void 0:n.verticalAnchor)&&void 0!==r?r:.5,orientation:J(null==n?void 0:n.orientation)},this.parameters.orientation!==q.ALWAYS&&this.parameters.orientation!==this.layer.orientation||this.buildConstraints()}destroy(){this.destroyConstraints(),super.destroy()}[N](t){this.parameters.orientation!==q.ALWAYS&&t!==this.parameters.orientation&&this.destroyConstraints()}[R](t){this.parameters.orientation!==q.ALWAYS&&t===this.parameters.orientation&&this.buildConstraints()}buildConstraints(){this.constraintX=new E(new b(this.elementOne[I]).plus(new b(this.elementOne[$]).multiply(this.parameters.horizontalAnchor)),y.Eq,new b(this.elementTwo[I]).plus(new b(this.elementTwo[$]).multiply(this.parameters.horizontalAnchor))),this.constraintY=new E(new b(this.elementOne[k]).plus(new b(this.elementOne[D]).multiply(this.parameters.verticalAnchor)),y.Eq,new b(this.elementTwo[k]).plus(new b(this.elementTwo[D]).multiply(this.parameters.verticalAnchor))),this.constraintW=new E(new b(this.elementOne[$]),y.Ge,new b(this.elementTwo[$])),this.constraintH=new E(new b(this.elementOne[D]),y.Ge,new b(this.elementTwo[D])),this.layer[V](this,this.constraintX),this.layer[V](this,this.constraintY),this.layer[V](this,this.constraintW),this.layer[V](this,this.constraintH),0!=this.parameters.isStrict&&(this.constraintStrict=new E(new b(this.elementOne[D]),y.Eq,new b(this.elementTwo[D]),g.strong),this.layer[V](this,this.constraintStrict))}destroyConstraints(){this.constraintX&&(this.layer[K](this,this.constraintX),this.constraintX=void 0),this.constraintY&&(this.layer[K](this,this.constraintY),this.constraintY=void 0),this.constraintW&&(this.layer[K](this,this.constraintW),this.constraintW=void 0),this.constraintH&&(this.layer[K](this,this.constraintH),this.constraintH=void 0),this.constraintStrict&&(this.layer[K](this,this.constraintStrict),this.constraintStrict=void 0)}}class ei extends xt{constructor(){super(),this.targetScreenHeight=1920,this.onResize=()=>{const t=this.calculateScale();this.resizeInternal(window.innerWidth*t,window.innerHeight*t)},this.onClick=t=>{if(this.behavior!==ut.INTERACTIVE)return;const i=t.target instanceof HTMLElement?t.target.getBoundingClientRect():null,n=i?t.clientX-i.left:t.clientX,s=i?i.bottom-t.clientY:window.innerHeight-t.clientY,o=this.calculateScale();this.clickInternal(n*o,s*o)},window.addEventListener("resize",this.onResize),window.addEventListener("click",this.onClick),this.onResize()}get tergetScreenHeight(){return this.targetScreenHeight}set tergetScreenHeight(t){this.targetScreenHeight=t,this.resizeInternal(window.innerWidth,window.innerHeight)}destroy(){window.removeEventListener("resize",this.onResize),window.removeEventListener("click",this.onClick),super.destroy()}calculateScale(){var t;return(null!==(t=this.tergetScreenHeight)&&void 0!==t?t:window.innerHeight)/window.innerHeight}}class hi extends xt{click(t,i){this.clickInternal(t,i)}resize(t,i){this.resizeInternal(t,i)}}export{Dt as UIAspectConstraint,ut as UIBehavior,Yt as UIConstraintBuilder,$t as UIConstraintBuilder2D,F as UIConstraintPower,G as UIConstraintRule,Pt as UICoverConstraint,Xt as UIDummy,si as UIElementBuilder,mt as UIElementEvent,ri as UIFitConstraint,ei as UIFullScreenLayer,rt as UIHeightConstraint,zt as UIHorizontalDistanceConstraint,Ot as UIHorizontalProportionConstraint,Ft as UIImage,hi as UIManualLayer,q as UIOrientation,oi as UIStackConstraintBuilder,_t as UIText,Tt as UIVerticalDistanceConstraint,It as UIVerticalProportionConstraint,kt as UIWidthConstraint};
1
+ import { Vector2, Box2, MathUtils, Scene, OrthographicCamera, Object3D, UniformsUtils, Matrix3, Color, ShaderMaterial, PlaneGeometry, Mesh, CanvasTexture, Texture } from 'three';
2
+
3
+ /*-----------------------------------------------------------------------------
4
+ | Copyright (c) 2014, Nucleic Development Team.
5
+ |
6
+ | Distributed under the terms of the Modified BSD License.
7
+ |
8
+ | The full license is in the file COPYING.txt, distributed with this software.
9
+ |----------------------------------------------------------------------------*/
10
+ function createMap() {
11
+ return new IndexedMap();
12
+ }
13
+ var IndexedMap = /** @class */ (function () {
14
+ function IndexedMap() {
15
+ this.index = {};
16
+ this.array = [];
17
+ }
18
+ /**
19
+ * Returns the number of items in the array.
20
+ */
21
+ IndexedMap.prototype.size = function () {
22
+ return this.array.length;
23
+ };
24
+ /**
25
+ * Returns true if the array is empty.
26
+ */
27
+ IndexedMap.prototype.empty = function () {
28
+ return this.array.length === 0;
29
+ };
30
+ /**
31
+ * Returns the item at the given array index.
32
+ *
33
+ * @param index The integer index of the desired item.
34
+ */
35
+ IndexedMap.prototype.itemAt = function (index) {
36
+ return this.array[index];
37
+ };
38
+ /**
39
+ * Returns true if the key is in the array, false otherwise.
40
+ *
41
+ * @param key The key to locate in the array.
42
+ */
43
+ IndexedMap.prototype.contains = function (key) {
44
+ return this.index[key.id()] !== undefined;
45
+ };
46
+ /**
47
+ * Returns the pair associated with the given key, or undefined.
48
+ *
49
+ * @param key The key to locate in the array.
50
+ */
51
+ IndexedMap.prototype.find = function (key) {
52
+ var i = this.index[key.id()];
53
+ return i === undefined ? undefined : this.array[i];
54
+ };
55
+ /**
56
+ * Returns the pair associated with the key if it exists.
57
+ *
58
+ * If the key does not exist, a new pair will be created and
59
+ * inserted using the value created by the given factory.
60
+ *
61
+ * @param key The key to locate in the array.
62
+ * @param factory The function which creates the default value.
63
+ */
64
+ IndexedMap.prototype.setDefault = function (key, factory) {
65
+ var i = this.index[key.id()];
66
+ if (i === undefined) {
67
+ var pair = new Pair(key, factory());
68
+ this.index[key.id()] = this.array.length;
69
+ this.array.push(pair);
70
+ return pair;
71
+ }
72
+ else {
73
+ return this.array[i];
74
+ }
75
+ };
76
+ /**
77
+ * Insert the pair into the array and return the pair.
78
+ *
79
+ * This will overwrite any existing entry in the array.
80
+ *
81
+ * @param key The key portion of the pair.
82
+ * @param value The value portion of the pair.
83
+ */
84
+ IndexedMap.prototype.insert = function (key, value) {
85
+ var pair = new Pair(key, value);
86
+ var i = this.index[key.id()];
87
+ if (i === undefined) {
88
+ this.index[key.id()] = this.array.length;
89
+ this.array.push(pair);
90
+ }
91
+ else {
92
+ this.array[i] = pair;
93
+ }
94
+ return pair;
95
+ };
96
+ /**
97
+ * Removes and returns the pair for the given key, or undefined.
98
+ *
99
+ * @param key The key to remove from the map.
100
+ */
101
+ IndexedMap.prototype.erase = function (key) {
102
+ var i = this.index[key.id()];
103
+ if (i === undefined) {
104
+ return undefined;
105
+ }
106
+ this.index[key.id()] = undefined;
107
+ var pair = this.array[i];
108
+ var last = this.array.pop();
109
+ if (pair !== last) {
110
+ this.array[i] = last;
111
+ this.index[last.first.id()] = i;
112
+ }
113
+ return pair;
114
+ };
115
+ /**
116
+ * Create a copy of this associative array.
117
+ */
118
+ IndexedMap.prototype.copy = function () {
119
+ var copy = new IndexedMap();
120
+ for (var i = 0; i < this.array.length; i++) {
121
+ var pair = this.array[i].copy();
122
+ copy.array[i] = pair;
123
+ copy.index[pair.first.id()] = i;
124
+ }
125
+ return copy;
126
+ };
127
+ return IndexedMap;
128
+ }());
129
+ /**
130
+ * A class which defines a generic pair object.
131
+ * @private
132
+ */
133
+ // tslint:disable: max-classes-per-file
134
+ var Pair = /** @class */ (function () {
135
+ /**
136
+ * Construct a new Pair object.
137
+ *
138
+ * @param first The first item of the pair.
139
+ * @param second The second item of the pair.
140
+ */
141
+ function Pair(first, second) {
142
+ this.first = first;
143
+ this.second = second;
144
+ }
145
+ /**
146
+ * Create a copy of the pair.
147
+ */
148
+ Pair.prototype.copy = function () { return new Pair(this.first, this.second); };
149
+ return Pair;
150
+ }());
151
+
152
+ /*-----------------------------------------------------------------------------
153
+ | Copyright (c) 2014, Nucleic Development Team.
154
+ |
155
+ | Distributed under the terms of the Modified BSD License.
156
+ |
157
+ | The full license is in the file COPYING.txt, distributed with this software.
158
+ |----------------------------------------------------------------------------*/
159
+ /**
160
+ * The primary user constraint variable.
161
+ *
162
+ * @class
163
+ * @param {String} [name=""] The name to associated with the variable.
164
+ */
165
+ var Variable = /** @class */ (function () {
166
+ function Variable(name) {
167
+ if (name === void 0) { name = ""; }
168
+ this._value = 0.0;
169
+ this._context = null;
170
+ this._id = VarId++;
171
+ this._name = name;
172
+ }
173
+ /**
174
+ * Returns the unique id number of the variable.
175
+ * @private
176
+ */
177
+ Variable.prototype.id = function () {
178
+ return this._id;
179
+ };
180
+ /**
181
+ * Returns the name of the variable.
182
+ *
183
+ * @return {String} name of the variable
184
+ */
185
+ Variable.prototype.name = function () {
186
+ return this._name;
187
+ };
188
+ /**
189
+ * Set the name of the variable.
190
+ *
191
+ * @param {String} name Name of the variable
192
+ */
193
+ Variable.prototype.setName = function (name) {
194
+ this._name = name;
195
+ };
196
+ /**
197
+ * Returns the user context object of the variable.
198
+ * @private
199
+ */
200
+ Variable.prototype.context = function () {
201
+ return this._context;
202
+ };
203
+ /**
204
+ * Set the user context object of the variable.
205
+ * @private
206
+ */
207
+ Variable.prototype.setContext = function (context) {
208
+ this._context = context;
209
+ };
210
+ /**
211
+ * Returns the value of the variable.
212
+ *
213
+ * @return {Number} Calculated value
214
+ */
215
+ Variable.prototype.value = function () {
216
+ return this._value;
217
+ };
218
+ /**
219
+ * Set the value of the variable.
220
+ * @private
221
+ */
222
+ Variable.prototype.setValue = function (value) {
223
+ this._value = value;
224
+ };
225
+ /**
226
+ * Creates a new Expression by adding a number, variable or expression
227
+ * to the variable.
228
+ *
229
+ * @param {Number|Variable|Expression} value Value to add.
230
+ * @return {Expression} expression
231
+ */
232
+ Variable.prototype.plus = function (value) {
233
+ return new Expression(this, value);
234
+ };
235
+ /**
236
+ * Creates a new Expression by substracting a number, variable or expression
237
+ * from the variable.
238
+ *
239
+ * @param {Number|Variable|Expression} value Value to substract.
240
+ * @return {Expression} expression
241
+ */
242
+ Variable.prototype.minus = function (value) {
243
+ return new Expression(this, typeof value === "number" ? -value : [-1, value]);
244
+ };
245
+ /**
246
+ * Creates a new Expression by multiplying with a fixed number.
247
+ *
248
+ * @param {Number} coefficient Coefficient to multiply with.
249
+ * @return {Expression} expression
250
+ */
251
+ Variable.prototype.multiply = function (coefficient) {
252
+ return new Expression([coefficient, this]);
253
+ };
254
+ /**
255
+ * Creates a new Expression by dividing with a fixed number.
256
+ *
257
+ * @param {Number} coefficient Coefficient to divide by.
258
+ * @return {Expression} expression
259
+ */
260
+ Variable.prototype.divide = function (coefficient) {
261
+ return new Expression([1 / coefficient, this]);
262
+ };
263
+ /**
264
+ * Returns the JSON representation of the variable.
265
+ * @private
266
+ */
267
+ Variable.prototype.toJSON = function () {
268
+ return {
269
+ name: this._name,
270
+ value: this._value,
271
+ };
272
+ };
273
+ Variable.prototype.toString = function () {
274
+ return this._context + "[" + this._name + ":" + this._value + "]";
275
+ };
276
+ return Variable;
277
+ }());
278
+ /**
279
+ * The internal variable id counter.
280
+ * @private
281
+ */
282
+ var VarId = 0;
283
+
284
+ /*-----------------------------------------------------------------------------
285
+ | Copyright (c) 2014, Nucleic Development Team.
286
+ |
287
+ | Distributed under the terms of the Modified BSD License.
288
+ |
289
+ | The full license is in the file COPYING.txt, distributed with this software.
290
+ |----------------------------------------------------------------------------*/
291
+ /**
292
+ * An expression of variable terms and a constant.
293
+ *
294
+ * The constructor accepts an arbitrary number of parameters,
295
+ * each of which must be one of the following types:
296
+ * - number
297
+ * - Variable
298
+ * - Expression
299
+ * - 2-tuple of [number, Variable|Expression]
300
+ *
301
+ * The parameters are summed. The tuples are multiplied.
302
+ *
303
+ * @class
304
+ * @param {...(number|Variable|Expression|Array)} args
305
+ */
306
+ var Expression = /** @class */ (function () {
307
+ function Expression() {
308
+ var parsed = parseArgs(arguments);
309
+ this._terms = parsed.terms;
310
+ this._constant = parsed.constant;
311
+ }
312
+ /**
313
+ * Returns the mapping of terms in the expression.
314
+ *
315
+ * This *must* be treated as const.
316
+ * @private
317
+ */
318
+ Expression.prototype.terms = function () {
319
+ return this._terms;
320
+ };
321
+ /**
322
+ * Returns the constant of the expression.
323
+ * @private
324
+ */
325
+ Expression.prototype.constant = function () {
326
+ return this._constant;
327
+ };
328
+ /**
329
+ * Returns the computed value of the expression.
330
+ *
331
+ * @private
332
+ * @return {Number} computed value of the expression
333
+ */
334
+ Expression.prototype.value = function () {
335
+ var result = this._constant;
336
+ for (var i = 0, n = this._terms.size(); i < n; i++) {
337
+ var pair = this._terms.itemAt(i);
338
+ result += pair.first.value() * pair.second;
339
+ }
340
+ return result;
341
+ };
342
+ /**
343
+ * Creates a new Expression by adding a number, variable or expression
344
+ * to the expression.
345
+ *
346
+ * @param {Number|Variable|Expression} value Value to add.
347
+ * @return {Expression} expression
348
+ */
349
+ Expression.prototype.plus = function (value) {
350
+ return new Expression(this, value);
351
+ };
352
+ /**
353
+ * Creates a new Expression by substracting a number, variable or expression
354
+ * from the expression.
355
+ *
356
+ * @param {Number|Variable|Expression} value Value to substract.
357
+ * @return {Expression} expression
358
+ */
359
+ Expression.prototype.minus = function (value) {
360
+ return new Expression(this, typeof value === "number" ? -value : [-1, value]);
361
+ };
362
+ /**
363
+ * Creates a new Expression by multiplying with a fixed number.
364
+ *
365
+ * @param {Number} coefficient Coefficient to multiply with.
366
+ * @return {Expression} expression
367
+ */
368
+ Expression.prototype.multiply = function (coefficient) {
369
+ return new Expression([coefficient, this]);
370
+ };
371
+ /**
372
+ * Creates a new Expression by dividing with a fixed number.
373
+ *
374
+ * @param {Number} coefficient Coefficient to divide by.
375
+ * @return {Expression} expression
376
+ */
377
+ Expression.prototype.divide = function (coefficient) {
378
+ return new Expression([1 / coefficient, this]);
379
+ };
380
+ Expression.prototype.isConstant = function () {
381
+ return this._terms.size() == 0;
382
+ };
383
+ Expression.prototype.toString = function () {
384
+ var result = this._terms.array.map(function (pair) {
385
+ return (pair.second + "*" + pair.first.toString());
386
+ }).join(" + ");
387
+ if (!this.isConstant() && this._constant !== 0) {
388
+ result += " + ";
389
+ }
390
+ result += this._constant;
391
+ return result;
392
+ };
393
+ return Expression;
394
+ }());
395
+ /**
396
+ * An internal argument parsing function.
397
+ * @private
398
+ */
399
+ function parseArgs(args) {
400
+ var constant = 0.0;
401
+ var factory = function () { return 0.0; };
402
+ var terms = createMap();
403
+ for (var i = 0, n = args.length; i < n; ++i) {
404
+ var item = args[i];
405
+ if (typeof item === "number") {
406
+ constant += item;
407
+ }
408
+ else if (item instanceof Variable) {
409
+ terms.setDefault(item, factory).second += 1.0;
410
+ }
411
+ else if (item instanceof Expression) {
412
+ constant += item.constant();
413
+ var terms2 = item.terms();
414
+ for (var j = 0, k = terms2.size(); j < k; j++) {
415
+ var termPair = terms2.itemAt(j);
416
+ terms.setDefault(termPair.first, factory).second += termPair.second;
417
+ }
418
+ }
419
+ else if (item instanceof Array) {
420
+ if (item.length !== 2) {
421
+ throw new Error("array must have length 2");
422
+ }
423
+ var value = item[0];
424
+ var value2 = item[1];
425
+ if (typeof value !== "number") {
426
+ throw new Error("array item 0 must be a number");
427
+ }
428
+ if (value2 instanceof Variable) {
429
+ terms.setDefault(value2, factory).second += value;
430
+ }
431
+ else if (value2 instanceof Expression) {
432
+ constant += (value2.constant() * value);
433
+ var terms2 = value2.terms();
434
+ for (var j = 0, k = terms2.size(); j < k; j++) {
435
+ var termPair = terms2.itemAt(j);
436
+ terms.setDefault(termPair.first, factory).second += (termPair.second * value);
437
+ }
438
+ }
439
+ else {
440
+ throw new Error("array item 1 must be a variable or expression");
441
+ }
442
+ }
443
+ else {
444
+ throw new Error("invalid Expression argument: " + item);
445
+ }
446
+ }
447
+ return { terms: terms, constant: constant };
448
+ }
449
+
450
+ /*-----------------------------------------------------------------------------
451
+ | Copyright (c) 2014, Nucleic Development Team.
452
+ |
453
+ | Distributed under the terms of the Modified BSD License.
454
+ |
455
+ | The full license is in the file COPYING.txt, distributed with this software.
456
+ |----------------------------------------------------------------------------*/
457
+ /**
458
+ * @class Strength
459
+ */
460
+ var Strength = /** @class */ (function () {
461
+ function Strength() {
462
+ }
463
+ /**
464
+ * Create a new symbolic strength.
465
+ *
466
+ * @param a strong
467
+ * @param b medium
468
+ * @param c weak
469
+ * @param [w] weight
470
+ * @return strength
471
+ */
472
+ Strength.create = function (a, b, c, w) {
473
+ if (w === void 0) { w = 1.0; }
474
+ var result = 0.0;
475
+ result += Math.max(0.0, Math.min(1000.0, a * w)) * 1000000.0;
476
+ result += Math.max(0.0, Math.min(1000.0, b * w)) * 1000.0;
477
+ result += Math.max(0.0, Math.min(1000.0, c * w));
478
+ return result;
479
+ };
480
+ /**
481
+ * Clip a symbolic strength to the allowed min and max.
482
+ * @private
483
+ */
484
+ Strength.clip = function (value) {
485
+ return Math.max(0.0, Math.min(Strength.required, value));
486
+ };
487
+ /**
488
+ * The 'required' symbolic strength.
489
+ */
490
+ Strength.required = Strength.create(1000.0, 1000.0, 1000.0);
491
+ /**
492
+ * The 'strong' symbolic strength.
493
+ */
494
+ Strength.strong = Strength.create(1.0, 0.0, 0.0);
495
+ /**
496
+ * The 'medium' symbolic strength.
497
+ */
498
+ Strength.medium = Strength.create(0.0, 1.0, 0.0);
499
+ /**
500
+ * The 'weak' symbolic strength.
501
+ */
502
+ Strength.weak = Strength.create(0.0, 0.0, 1.0);
503
+ return Strength;
504
+ }());
505
+
506
+ /*-----------------------------------------------------------------------------
507
+ | Copyright (c) 2014, Nucleic Development Team.
508
+ |
509
+ | Distributed under the terms of the Modified BSD License.
510
+ |
511
+ | The full license is in the file COPYING.txt, distributed with this software.
512
+ |----------------------------------------------------------------------------*/
513
+ /**
514
+ * An enum defining the linear constraint operators.
515
+ *
516
+ * |Value|Operator|Description|
517
+ * |----|-----|-----|
518
+ * |`Le`|<=|Less than equal|
519
+ * |`Ge`|>=|Greater than equal|
520
+ * |`Eq`|==|Equal|
521
+ *
522
+ * @enum {Number}
523
+ */
524
+ var Operator;
525
+ (function (Operator) {
526
+ Operator[Operator["Le"] = 0] = "Le";
527
+ Operator[Operator["Ge"] = 1] = "Ge";
528
+ Operator[Operator["Eq"] = 2] = "Eq";
529
+ })(Operator || (Operator = {}));
530
+ /**
531
+ * A linear constraint equation.
532
+ *
533
+ * A constraint equation is composed of an expression, an operator,
534
+ * and a strength. The RHS of the equation is implicitly zero.
535
+ *
536
+ * @class
537
+ * @param {Expression} expression The constraint expression (LHS).
538
+ * @param {Operator} operator The equation operator.
539
+ * @param {Expression} [rhs] Right hand side of the expression.
540
+ * @param {Number} [strength=Strength.required] The strength of the constraint.
541
+ */
542
+ var Constraint = /** @class */ (function () {
543
+ function Constraint(expression, operator, rhs, strength) {
544
+ if (strength === void 0) { strength = Strength.required; }
545
+ this._id = CnId++;
546
+ this._operator = operator;
547
+ this._strength = Strength.clip(strength);
548
+ if ((rhs === undefined) && (expression instanceof Expression)) {
549
+ this._expression = expression;
550
+ }
551
+ else {
552
+ this._expression = expression.minus(rhs);
553
+ }
554
+ }
555
+ /**
556
+ * Returns the unique id number of the constraint.
557
+ * @private
558
+ */
559
+ Constraint.prototype.id = function () {
560
+ return this._id;
561
+ };
562
+ /**
563
+ * Returns the expression of the constraint.
564
+ *
565
+ * @return {Expression} expression
566
+ */
567
+ Constraint.prototype.expression = function () {
568
+ return this._expression;
569
+ };
570
+ /**
571
+ * Returns the relational operator of the constraint.
572
+ *
573
+ * @return {Operator} linear constraint operator
574
+ */
575
+ Constraint.prototype.op = function () {
576
+ return this._operator;
577
+ };
578
+ /**
579
+ * Returns the strength of the constraint.
580
+ *
581
+ * @return {Number} strength
582
+ */
583
+ Constraint.prototype.strength = function () {
584
+ return this._strength;
585
+ };
586
+ Constraint.prototype.toString = function () {
587
+ return this._expression.toString() + " " + ["<=", ">=", "="][this._operator] + " 0 (" + this._strength.toString() + ")";
588
+ };
589
+ return Constraint;
590
+ }());
591
+ /**
592
+ * The internal constraint id counter.
593
+ * @private
594
+ */
595
+ var CnId = 0;
596
+
597
+ /*-----------------------------------------------------------------------------
598
+ | Copyright (c) 2014, Nucleic Development Team.
599
+ |
600
+ | Distributed under the terms of the Modified BSD License.
601
+ |
602
+ | The full license is in the file COPYING.txt, distributed with this software.
603
+ |----------------------------------------------------------------------------*/
604
+ /**
605
+ * The constraint solver class.
606
+ *
607
+ * @class
608
+ */
609
+ var Solver = /** @class */ (function () {
610
+ /**
611
+ * Construct a new Solver.
612
+ */
613
+ function Solver() {
614
+ this._cnMap = createCnMap();
615
+ this._rowMap = createRowMap();
616
+ this._varMap = createVarMap();
617
+ this._editMap = createEditMap();
618
+ this._infeasibleRows = [];
619
+ this._objective = new Row();
620
+ this._artificial = null;
621
+ this._idTick = 0;
622
+ }
623
+ /**
624
+ * Creates and add a constraint to the solver.
625
+ *
626
+ * @param {Expression|Variable} lhs Left hand side of the expression
627
+ * @param {Operator} operator Operator
628
+ * @param {Expression|Variable|Number} rhs Right hand side of the expression
629
+ * @param {Number} [strength=Strength.required] Strength
630
+ */
631
+ Solver.prototype.createConstraint = function (lhs, operator, rhs, strength) {
632
+ if (strength === void 0) { strength = Strength.required; }
633
+ var cn = new Constraint(lhs, operator, rhs, strength);
634
+ this.addConstraint(cn);
635
+ return cn;
636
+ };
637
+ /**
638
+ * Add a constraint to the solver.
639
+ *
640
+ * @param {Constraint} constraint Constraint to add to the solver
641
+ */
642
+ Solver.prototype.addConstraint = function (constraint) {
643
+ var cnPair = this._cnMap.find(constraint);
644
+ if (cnPair !== undefined) {
645
+ throw new Error("duplicate constraint");
646
+ }
647
+ // Creating a row causes symbols to be reserved for the variables
648
+ // in the constraint. If this method exits with an exception,
649
+ // then its possible those variables will linger in the var map.
650
+ // Since its likely that those variables will be used in other
651
+ // constraints and since exceptional conditions are uncommon,
652
+ // i'm not too worried about aggressive cleanup of the var map.
653
+ var data = this._createRow(constraint);
654
+ var row = data.row;
655
+ var tag = data.tag;
656
+ var subject = this._chooseSubject(row, tag);
657
+ // If chooseSubject couldnt find a valid entering symbol, one
658
+ // last option is available if the entire row is composed of
659
+ // dummy variables. If the constant of the row is zero, then
660
+ // this represents redundant constraints and the new dummy
661
+ // marker can enter the basis. If the constant is non-zero,
662
+ // then it represents an unsatisfiable constraint.
663
+ if (subject.type() === SymbolType.Invalid && row.allDummies()) {
664
+ if (!nearZero(row.constant())) {
665
+ throw new Error("unsatisfiable constraint");
666
+ }
667
+ else {
668
+ subject = tag.marker;
669
+ }
670
+ }
671
+ // If an entering symbol still isn't found, then the row must
672
+ // be added using an artificial variable. If that fails, then
673
+ // the row represents an unsatisfiable constraint.
674
+ if (subject.type() === SymbolType.Invalid) {
675
+ if (!this._addWithArtificialVariable(row)) {
676
+ throw new Error("unsatisfiable constraint");
677
+ }
678
+ }
679
+ else {
680
+ row.solveFor(subject);
681
+ this._substitute(subject, row);
682
+ this._rowMap.insert(subject, row);
683
+ }
684
+ this._cnMap.insert(constraint, tag);
685
+ // Optimizing after each constraint is added performs less
686
+ // aggregate work due to a smaller average system size. It
687
+ // also ensures the solver remains in a consistent state.
688
+ this._optimize(this._objective);
689
+ };
690
+ /**
691
+ * Remove a constraint from the solver.
692
+ *
693
+ * @param {Constraint} constraint Constraint to remove from the solver
694
+ */
695
+ Solver.prototype.removeConstraint = function (constraint) {
696
+ var cnPair = this._cnMap.erase(constraint);
697
+ if (cnPair === undefined) {
698
+ throw new Error("unknown constraint");
699
+ }
700
+ // Remove the error effects from the objective function
701
+ // *before* pivoting, or substitutions into the objective
702
+ // will lead to incorrect solver results.
703
+ this._removeConstraintEffects(constraint, cnPair.second);
704
+ // If the marker is basic, simply drop the row. Otherwise,
705
+ // pivot the marker into the basis and then drop the row.
706
+ var marker = cnPair.second.marker;
707
+ var rowPair = this._rowMap.erase(marker);
708
+ if (rowPair === undefined) {
709
+ var leaving = this._getMarkerLeavingSymbol(marker);
710
+ if (leaving.type() === SymbolType.Invalid) {
711
+ throw new Error("failed to find leaving row");
712
+ }
713
+ rowPair = this._rowMap.erase(leaving);
714
+ rowPair.second.solveForEx(leaving, marker);
715
+ this._substitute(marker, rowPair.second);
716
+ }
717
+ // Optimizing after each constraint is removed ensures that the
718
+ // solver remains consistent. It makes the solver api easier to
719
+ // use at a small tradeoff for speed.
720
+ this._optimize(this._objective);
721
+ };
722
+ /**
723
+ * Test whether the solver contains the constraint.
724
+ *
725
+ * @param {Constraint} constraint Constraint to test for
726
+ * @return {Bool} true or false
727
+ */
728
+ Solver.prototype.hasConstraint = function (constraint) {
729
+ return this._cnMap.contains(constraint);
730
+ };
731
+ /**
732
+ * Add an edit variable to the solver.
733
+ *
734
+ * @param {Variable} variable Edit variable to add to the solver
735
+ * @param {Number} strength Strength, should be less than `Strength.required`
736
+ */
737
+ Solver.prototype.addEditVariable = function (variable, strength) {
738
+ var editPair = this._editMap.find(variable);
739
+ if (editPair !== undefined) {
740
+ throw new Error("duplicate edit variable");
741
+ }
742
+ strength = Strength.clip(strength);
743
+ if (strength === Strength.required) {
744
+ throw new Error("bad required strength");
745
+ }
746
+ var expr = new Expression(variable);
747
+ var cn = new Constraint(expr, Operator.Eq, undefined, strength);
748
+ this.addConstraint(cn);
749
+ var tag = this._cnMap.find(cn).second;
750
+ var info = { tag: tag, constraint: cn, constant: 0.0 };
751
+ this._editMap.insert(variable, info);
752
+ };
753
+ /**
754
+ * Remove an edit variable from the solver.
755
+ *
756
+ * @param {Variable} variable Edit variable to remove from the solver
757
+ */
758
+ Solver.prototype.removeEditVariable = function (variable) {
759
+ var editPair = this._editMap.erase(variable);
760
+ if (editPair === undefined) {
761
+ throw new Error("unknown edit variable");
762
+ }
763
+ this.removeConstraint(editPair.second.constraint);
764
+ };
765
+ /**
766
+ * Test whether the solver contains the edit variable.
767
+ *
768
+ * @param {Variable} variable Edit variable to test for
769
+ * @return {Bool} true or false
770
+ */
771
+ Solver.prototype.hasEditVariable = function (variable) {
772
+ return this._editMap.contains(variable);
773
+ };
774
+ /**
775
+ * Suggest the value of an edit variable.
776
+ *
777
+ * @param {Variable} variable Edit variable to suggest a value for
778
+ * @param {Number} value Suggested value
779
+ */
780
+ Solver.prototype.suggestValue = function (variable, value) {
781
+ var editPair = this._editMap.find(variable);
782
+ if (editPair === undefined) {
783
+ throw new Error("unknown edit variable");
784
+ }
785
+ var rows = this._rowMap;
786
+ var info = editPair.second;
787
+ var delta = value - info.constant;
788
+ info.constant = value;
789
+ // Check first if the positive error variable is basic.
790
+ var marker = info.tag.marker;
791
+ var rowPair = rows.find(marker);
792
+ if (rowPair !== undefined) {
793
+ if (rowPair.second.add(-delta) < 0.0) {
794
+ this._infeasibleRows.push(marker);
795
+ }
796
+ this._dualOptimize();
797
+ return;
798
+ }
799
+ // Check next if the negative error variable is basic.
800
+ var other = info.tag.other;
801
+ rowPair = rows.find(other);
802
+ if (rowPair !== undefined) {
803
+ if (rowPair.second.add(delta) < 0.0) {
804
+ this._infeasibleRows.push(other);
805
+ }
806
+ this._dualOptimize();
807
+ return;
808
+ }
809
+ // Otherwise update each row where the error variables exist.
810
+ for (var i = 0, n = rows.size(); i < n; ++i) {
811
+ var rowPair_1 = rows.itemAt(i);
812
+ var row = rowPair_1.second;
813
+ var coeff = row.coefficientFor(marker);
814
+ if (coeff !== 0.0 && row.add(delta * coeff) < 0.0 &&
815
+ rowPair_1.first.type() !== SymbolType.External) {
816
+ this._infeasibleRows.push(rowPair_1.first);
817
+ }
818
+ }
819
+ this._dualOptimize();
820
+ };
821
+ /**
822
+ * Update the values of the variables.
823
+ */
824
+ Solver.prototype.updateVariables = function () {
825
+ var vars = this._varMap;
826
+ var rows = this._rowMap;
827
+ for (var i = 0, n = vars.size(); i < n; ++i) {
828
+ var pair = vars.itemAt(i);
829
+ var rowPair = rows.find(pair.second);
830
+ if (rowPair !== undefined) {
831
+ pair.first.setValue(rowPair.second.constant());
832
+ }
833
+ else {
834
+ pair.first.setValue(0.0);
835
+ }
836
+ }
837
+ };
838
+ /**
839
+ * Get the symbol for the given variable.
840
+ *
841
+ * If a symbol does not exist for the variable, one will be created.
842
+ * @private
843
+ */
844
+ Solver.prototype._getVarSymbol = function (variable) {
845
+ var _this = this;
846
+ var factory = function () { return _this._makeSymbol(SymbolType.External); };
847
+ return this._varMap.setDefault(variable, factory).second;
848
+ };
849
+ /**
850
+ * Create a new Row object for the given constraint.
851
+ *
852
+ * The terms in the constraint will be converted to cells in the row.
853
+ * Any term in the constraint with a coefficient of zero is ignored.
854
+ * This method uses the `_getVarSymbol` method to get the symbol for
855
+ * the variables added to the row. If the symbol for a given cell
856
+ * variable is basic, the cell variable will be substituted with the
857
+ * basic row.
858
+ *
859
+ * The necessary slack and error variables will be added to the row.
860
+ * If the constant for the row is negative, the sign for the row
861
+ * will be inverted so the constant becomes positive.
862
+ *
863
+ * Returns the created Row and the tag for tracking the constraint.
864
+ * @private
865
+ */
866
+ Solver.prototype._createRow = function (constraint) {
867
+ var expr = constraint.expression();
868
+ var row = new Row(expr.constant());
869
+ // Substitute the current basic variables into the row.
870
+ var terms = expr.terms();
871
+ for (var i = 0, n = terms.size(); i < n; ++i) {
872
+ var termPair = terms.itemAt(i);
873
+ if (!nearZero(termPair.second)) {
874
+ var symbol = this._getVarSymbol(termPair.first);
875
+ var basicPair = this._rowMap.find(symbol);
876
+ if (basicPair !== undefined) {
877
+ row.insertRow(basicPair.second, termPair.second);
878
+ }
879
+ else {
880
+ row.insertSymbol(symbol, termPair.second);
881
+ }
882
+ }
883
+ }
884
+ // Add the necessary slack, error, and dummy variables.
885
+ var objective = this._objective;
886
+ var strength = constraint.strength();
887
+ var tag = { marker: INVALID_SYMBOL, other: INVALID_SYMBOL };
888
+ switch (constraint.op()) {
889
+ case Operator.Le:
890
+ case Operator.Ge:
891
+ {
892
+ var coeff = constraint.op() === Operator.Le ? 1.0 : -1;
893
+ var slack = this._makeSymbol(SymbolType.Slack);
894
+ tag.marker = slack;
895
+ row.insertSymbol(slack, coeff);
896
+ if (strength < Strength.required) {
897
+ var error = this._makeSymbol(SymbolType.Error);
898
+ tag.other = error;
899
+ row.insertSymbol(error, -coeff);
900
+ objective.insertSymbol(error, strength);
901
+ }
902
+ break;
903
+ }
904
+ case Operator.Eq:
905
+ {
906
+ if (strength < Strength.required) {
907
+ var errplus = this._makeSymbol(SymbolType.Error);
908
+ var errminus = this._makeSymbol(SymbolType.Error);
909
+ tag.marker = errplus;
910
+ tag.other = errminus;
911
+ row.insertSymbol(errplus, -1); // v = eplus - eminus
912
+ row.insertSymbol(errminus, 1.0); // v - eplus + eminus = 0
913
+ objective.insertSymbol(errplus, strength);
914
+ objective.insertSymbol(errminus, strength);
915
+ }
916
+ else {
917
+ var dummy = this._makeSymbol(SymbolType.Dummy);
918
+ tag.marker = dummy;
919
+ row.insertSymbol(dummy);
920
+ }
921
+ break;
922
+ }
923
+ }
924
+ // Ensure the row has a positive constant.
925
+ if (row.constant() < 0.0) {
926
+ row.reverseSign();
927
+ }
928
+ return { row: row, tag: tag };
929
+ };
930
+ /**
931
+ * Choose the subject for solving for the row.
932
+ *
933
+ * This method will choose the best subject for using as the solve
934
+ * target for the row. An invalid symbol will be returned if there
935
+ * is no valid target.
936
+ *
937
+ * The symbols are chosen according to the following precedence:
938
+ *
939
+ * 1) The first symbol representing an external variable.
940
+ * 2) A negative slack or error tag variable.
941
+ *
942
+ * If a subject cannot be found, an invalid symbol will be returned.
943
+ *
944
+ * @private
945
+ */
946
+ Solver.prototype._chooseSubject = function (row, tag) {
947
+ var cells = row.cells();
948
+ for (var i = 0, n = cells.size(); i < n; ++i) {
949
+ var pair = cells.itemAt(i);
950
+ if (pair.first.type() === SymbolType.External) {
951
+ return pair.first;
952
+ }
953
+ }
954
+ var type = tag.marker.type();
955
+ if (type === SymbolType.Slack || type === SymbolType.Error) {
956
+ if (row.coefficientFor(tag.marker) < 0.0) {
957
+ return tag.marker;
958
+ }
959
+ }
960
+ type = tag.other.type();
961
+ if (type === SymbolType.Slack || type === SymbolType.Error) {
962
+ if (row.coefficientFor(tag.other) < 0.0) {
963
+ return tag.other;
964
+ }
965
+ }
966
+ return INVALID_SYMBOL;
967
+ };
968
+ /**
969
+ * Add the row to the tableau using an artificial variable.
970
+ *
971
+ * This will return false if the constraint cannot be satisfied.
972
+ *
973
+ * @private
974
+ */
975
+ Solver.prototype._addWithArtificialVariable = function (row) {
976
+ // Create and add the artificial variable to the tableau.
977
+ var art = this._makeSymbol(SymbolType.Slack);
978
+ this._rowMap.insert(art, row.copy());
979
+ this._artificial = row.copy();
980
+ // Optimize the artificial objective. This is successful
981
+ // only if the artificial objective is optimized to zero.
982
+ this._optimize(this._artificial);
983
+ var success = nearZero(this._artificial.constant());
984
+ this._artificial = null;
985
+ // If the artificial variable is basic, pivot the row so that
986
+ // it becomes non-basic. If the row is constant, exit early.
987
+ var pair = this._rowMap.erase(art);
988
+ if (pair !== undefined) {
989
+ var basicRow = pair.second;
990
+ if (basicRow.isConstant()) {
991
+ return success;
992
+ }
993
+ var entering = this._anyPivotableSymbol(basicRow);
994
+ if (entering.type() === SymbolType.Invalid) {
995
+ return false; // unsatisfiable (will this ever happen?)
996
+ }
997
+ basicRow.solveForEx(art, entering);
998
+ this._substitute(entering, basicRow);
999
+ this._rowMap.insert(entering, basicRow);
1000
+ }
1001
+ // Remove the artificial variable from the tableau.
1002
+ var rows = this._rowMap;
1003
+ for (var i = 0, n = rows.size(); i < n; ++i) {
1004
+ rows.itemAt(i).second.removeSymbol(art);
1005
+ }
1006
+ this._objective.removeSymbol(art);
1007
+ return success;
1008
+ };
1009
+ /**
1010
+ * Substitute the parametric symbol with the given row.
1011
+ *
1012
+ * This method will substitute all instances of the parametric symbol
1013
+ * in the tableau and the objective function with the given row.
1014
+ *
1015
+ * @private
1016
+ */
1017
+ Solver.prototype._substitute = function (symbol, row) {
1018
+ var rows = this._rowMap;
1019
+ for (var i = 0, n = rows.size(); i < n; ++i) {
1020
+ var pair = rows.itemAt(i);
1021
+ pair.second.substitute(symbol, row);
1022
+ if (pair.second.constant() < 0.0 &&
1023
+ pair.first.type() !== SymbolType.External) {
1024
+ this._infeasibleRows.push(pair.first);
1025
+ }
1026
+ }
1027
+ this._objective.substitute(symbol, row);
1028
+ if (this._artificial) {
1029
+ this._artificial.substitute(symbol, row);
1030
+ }
1031
+ };
1032
+ /**
1033
+ * Optimize the system for the given objective function.
1034
+ *
1035
+ * This method performs iterations of Phase 2 of the simplex method
1036
+ * until the objective function reaches a minimum.
1037
+ *
1038
+ * @private
1039
+ */
1040
+ Solver.prototype._optimize = function (objective) {
1041
+ while (true) {
1042
+ var entering = this._getEnteringSymbol(objective);
1043
+ if (entering.type() === SymbolType.Invalid) {
1044
+ return;
1045
+ }
1046
+ var leaving = this._getLeavingSymbol(entering);
1047
+ if (leaving.type() === SymbolType.Invalid) {
1048
+ throw new Error("the objective is unbounded");
1049
+ }
1050
+ // pivot the entering symbol into the basis
1051
+ var row = this._rowMap.erase(leaving).second;
1052
+ row.solveForEx(leaving, entering);
1053
+ this._substitute(entering, row);
1054
+ this._rowMap.insert(entering, row);
1055
+ }
1056
+ };
1057
+ /**
1058
+ * Optimize the system using the dual of the simplex method.
1059
+ *
1060
+ * The current state of the system should be such that the objective
1061
+ * function is optimal, but not feasible. This method will perform
1062
+ * an iteration of the dual simplex method to make the solution both
1063
+ * optimal and feasible.
1064
+ *
1065
+ * @private
1066
+ */
1067
+ Solver.prototype._dualOptimize = function () {
1068
+ var rows = this._rowMap;
1069
+ var infeasible = this._infeasibleRows;
1070
+ while (infeasible.length !== 0) {
1071
+ var leaving = infeasible.pop();
1072
+ var pair = rows.find(leaving);
1073
+ if (pair !== undefined && pair.second.constant() < 0.0) {
1074
+ var entering = this._getDualEnteringSymbol(pair.second);
1075
+ if (entering.type() === SymbolType.Invalid) {
1076
+ throw new Error("dual optimize failed");
1077
+ }
1078
+ // pivot the entering symbol into the basis
1079
+ var row = pair.second;
1080
+ rows.erase(leaving);
1081
+ row.solveForEx(leaving, entering);
1082
+ this._substitute(entering, row);
1083
+ rows.insert(entering, row);
1084
+ }
1085
+ }
1086
+ };
1087
+ /**
1088
+ * Compute the entering variable for a pivot operation.
1089
+ *
1090
+ * This method will return first symbol in the objective function which
1091
+ * is non-dummy and has a coefficient less than zero. If no symbol meets
1092
+ * the criteria, it means the objective function is at a minimum, and an
1093
+ * invalid symbol is returned.
1094
+ *
1095
+ * @private
1096
+ */
1097
+ Solver.prototype._getEnteringSymbol = function (objective) {
1098
+ var cells = objective.cells();
1099
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1100
+ var pair = cells.itemAt(i);
1101
+ var symbol = pair.first;
1102
+ if (pair.second < 0.0 && symbol.type() !== SymbolType.Dummy) {
1103
+ return symbol;
1104
+ }
1105
+ }
1106
+ return INVALID_SYMBOL;
1107
+ };
1108
+ /**
1109
+ * Compute the entering symbol for the dual optimize operation.
1110
+ *
1111
+ * This method will return the symbol in the row which has a positive
1112
+ * coefficient and yields the minimum ratio for its respective symbol
1113
+ * in the objective function. The provided row *must* be infeasible.
1114
+ * If no symbol is found which meats the criteria, an invalid symbol
1115
+ * is returned.
1116
+ *
1117
+ * @private
1118
+ */
1119
+ Solver.prototype._getDualEnteringSymbol = function (row) {
1120
+ var ratio = Number.MAX_VALUE;
1121
+ var entering = INVALID_SYMBOL;
1122
+ var cells = row.cells();
1123
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1124
+ var pair = cells.itemAt(i);
1125
+ var symbol = pair.first;
1126
+ var c = pair.second;
1127
+ if (c > 0.0 && symbol.type() !== SymbolType.Dummy) {
1128
+ var coeff = this._objective.coefficientFor(symbol);
1129
+ var r = coeff / c;
1130
+ if (r < ratio) {
1131
+ ratio = r;
1132
+ entering = symbol;
1133
+ }
1134
+ }
1135
+ }
1136
+ return entering;
1137
+ };
1138
+ /**
1139
+ * Compute the symbol for pivot exit row.
1140
+ *
1141
+ * This method will return the symbol for the exit row in the row
1142
+ * map. If no appropriate exit symbol is found, an invalid symbol
1143
+ * will be returned. This indicates that the objective function is
1144
+ * unbounded.
1145
+ *
1146
+ * @private
1147
+ */
1148
+ Solver.prototype._getLeavingSymbol = function (entering) {
1149
+ var ratio = Number.MAX_VALUE;
1150
+ var found = INVALID_SYMBOL;
1151
+ var rows = this._rowMap;
1152
+ for (var i = 0, n = rows.size(); i < n; ++i) {
1153
+ var pair = rows.itemAt(i);
1154
+ var symbol = pair.first;
1155
+ if (symbol.type() !== SymbolType.External) {
1156
+ var row = pair.second;
1157
+ var temp = row.coefficientFor(entering);
1158
+ if (temp < 0.0) {
1159
+ var temp_ratio = -row.constant() / temp;
1160
+ if (temp_ratio < ratio) {
1161
+ ratio = temp_ratio;
1162
+ found = symbol;
1163
+ }
1164
+ }
1165
+ }
1166
+ }
1167
+ return found;
1168
+ };
1169
+ /**
1170
+ * Compute the leaving symbol for a marker variable.
1171
+ *
1172
+ * This method will return a symbol corresponding to a basic row
1173
+ * which holds the given marker variable. The row will be chosen
1174
+ * according to the following precedence:
1175
+ *
1176
+ * 1) The row with a restricted basic varible and a negative coefficient
1177
+ * for the marker with the smallest ratio of -constant / coefficient.
1178
+ *
1179
+ * 2) The row with a restricted basic variable and the smallest ratio
1180
+ * of constant / coefficient.
1181
+ *
1182
+ * 3) The last unrestricted row which contains the marker.
1183
+ *
1184
+ * If the marker does not exist in any row, an invalid symbol will be
1185
+ * returned. This indicates an internal solver error since the marker
1186
+ * *should* exist somewhere in the tableau.
1187
+ *
1188
+ * @private
1189
+ */
1190
+ Solver.prototype._getMarkerLeavingSymbol = function (marker) {
1191
+ var dmax = Number.MAX_VALUE;
1192
+ var r1 = dmax;
1193
+ var r2 = dmax;
1194
+ var invalid = INVALID_SYMBOL;
1195
+ var first = invalid;
1196
+ var second = invalid;
1197
+ var third = invalid;
1198
+ var rows = this._rowMap;
1199
+ for (var i = 0, n = rows.size(); i < n; ++i) {
1200
+ var pair = rows.itemAt(i);
1201
+ var row = pair.second;
1202
+ var c = row.coefficientFor(marker);
1203
+ if (c === 0.0) {
1204
+ continue;
1205
+ }
1206
+ var symbol = pair.first;
1207
+ if (symbol.type() === SymbolType.External) {
1208
+ third = symbol;
1209
+ }
1210
+ else if (c < 0.0) {
1211
+ var r = -row.constant() / c;
1212
+ if (r < r1) {
1213
+ r1 = r;
1214
+ first = symbol;
1215
+ }
1216
+ }
1217
+ else {
1218
+ var r = row.constant() / c;
1219
+ if (r < r2) {
1220
+ r2 = r;
1221
+ second = symbol;
1222
+ }
1223
+ }
1224
+ }
1225
+ if (first !== invalid) {
1226
+ return first;
1227
+ }
1228
+ if (second !== invalid) {
1229
+ return second;
1230
+ }
1231
+ return third;
1232
+ };
1233
+ /**
1234
+ * Remove the effects of a constraint on the objective function.
1235
+ *
1236
+ * @private
1237
+ */
1238
+ Solver.prototype._removeConstraintEffects = function (cn, tag) {
1239
+ if (tag.marker.type() === SymbolType.Error) {
1240
+ this._removeMarkerEffects(tag.marker, cn.strength());
1241
+ }
1242
+ if (tag.other.type() === SymbolType.Error) {
1243
+ this._removeMarkerEffects(tag.other, cn.strength());
1244
+ }
1245
+ };
1246
+ /**
1247
+ * Remove the effects of an error marker on the objective function.
1248
+ *
1249
+ * @private
1250
+ */
1251
+ Solver.prototype._removeMarkerEffects = function (marker, strength) {
1252
+ var pair = this._rowMap.find(marker);
1253
+ if (pair !== undefined) {
1254
+ this._objective.insertRow(pair.second, -strength);
1255
+ }
1256
+ else {
1257
+ this._objective.insertSymbol(marker, -strength);
1258
+ }
1259
+ };
1260
+ /**
1261
+ * Get the first Slack or Error symbol in the row.
1262
+ *
1263
+ * If no such symbol is present, an invalid symbol will be returned.
1264
+ *
1265
+ * @private
1266
+ */
1267
+ Solver.prototype._anyPivotableSymbol = function (row) {
1268
+ var cells = row.cells();
1269
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1270
+ var pair = cells.itemAt(i);
1271
+ var type = pair.first.type();
1272
+ if (type === SymbolType.Slack || type === SymbolType.Error) {
1273
+ return pair.first;
1274
+ }
1275
+ }
1276
+ return INVALID_SYMBOL;
1277
+ };
1278
+ /**
1279
+ * Returns a new Symbol of the given type.
1280
+ *
1281
+ * @private
1282
+ */
1283
+ Solver.prototype._makeSymbol = function (type) {
1284
+ return new Symbol$1(type, this._idTick++);
1285
+ };
1286
+ return Solver;
1287
+ }());
1288
+ /**
1289
+ * Test whether a value is approximately zero.
1290
+ * @private
1291
+ */
1292
+ function nearZero(value) {
1293
+ var eps = 1.0e-8;
1294
+ return value < 0.0 ? -value < eps : value < eps;
1295
+ }
1296
+ /**
1297
+ * An internal function for creating a constraint map.
1298
+ * @private
1299
+ */
1300
+ function createCnMap() {
1301
+ return createMap();
1302
+ }
1303
+ /**
1304
+ * An internal function for creating a row map.
1305
+ * @private
1306
+ */
1307
+ function createRowMap() {
1308
+ return createMap();
1309
+ }
1310
+ /**
1311
+ * An internal function for creating a variable map.
1312
+ * @private
1313
+ */
1314
+ function createVarMap() {
1315
+ return createMap();
1316
+ }
1317
+ /**
1318
+ * An internal function for creating an edit map.
1319
+ * @private
1320
+ */
1321
+ function createEditMap() {
1322
+ return createMap();
1323
+ }
1324
+ /**
1325
+ * An enum defining the available symbol types.
1326
+ * @private
1327
+ */
1328
+ var SymbolType;
1329
+ (function (SymbolType) {
1330
+ SymbolType[SymbolType["Invalid"] = 0] = "Invalid";
1331
+ SymbolType[SymbolType["External"] = 1] = "External";
1332
+ SymbolType[SymbolType["Slack"] = 2] = "Slack";
1333
+ SymbolType[SymbolType["Error"] = 3] = "Error";
1334
+ SymbolType[SymbolType["Dummy"] = 4] = "Dummy";
1335
+ })(SymbolType || (SymbolType = {}));
1336
+ /**
1337
+ * An internal class representing a symbol in the solver.
1338
+ * @private
1339
+ */
1340
+ var Symbol$1 = /** @class */ (function () {
1341
+ /**
1342
+ * Construct a new Symbol
1343
+ *
1344
+ * @param [type] The type of the symbol.
1345
+ * @param [id] The unique id number of the symbol.
1346
+ */
1347
+ function Symbol(type, id) {
1348
+ this._id = id;
1349
+ this._type = type;
1350
+ }
1351
+ /**
1352
+ * Returns the unique id number of the symbol.
1353
+ */
1354
+ Symbol.prototype.id = function () {
1355
+ return this._id;
1356
+ };
1357
+ /**
1358
+ * Returns the type of the symbol.
1359
+ */
1360
+ Symbol.prototype.type = function () {
1361
+ return this._type;
1362
+ };
1363
+ return Symbol;
1364
+ }());
1365
+ /**
1366
+ * A static invalid symbol
1367
+ * @private
1368
+ */
1369
+ var INVALID_SYMBOL = new Symbol$1(SymbolType.Invalid, -1);
1370
+ /**
1371
+ * An internal row class used by the solver.
1372
+ * @private
1373
+ */
1374
+ var Row = /** @class */ (function () {
1375
+ /**
1376
+ * Construct a new Row.
1377
+ */
1378
+ function Row(constant) {
1379
+ if (constant === void 0) { constant = 0.0; }
1380
+ this._cellMap = createMap();
1381
+ this._constant = constant;
1382
+ }
1383
+ /**
1384
+ * Returns the mapping of symbols to coefficients.
1385
+ */
1386
+ Row.prototype.cells = function () {
1387
+ return this._cellMap;
1388
+ };
1389
+ /**
1390
+ * Returns the constant for the row.
1391
+ */
1392
+ Row.prototype.constant = function () {
1393
+ return this._constant;
1394
+ };
1395
+ /**
1396
+ * Returns true if the row is a constant value.
1397
+ */
1398
+ Row.prototype.isConstant = function () {
1399
+ return this._cellMap.empty();
1400
+ };
1401
+ /**
1402
+ * Returns true if the Row has all dummy symbols.
1403
+ */
1404
+ Row.prototype.allDummies = function () {
1405
+ var cells = this._cellMap;
1406
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1407
+ var pair = cells.itemAt(i);
1408
+ if (pair.first.type() !== SymbolType.Dummy) {
1409
+ return false;
1410
+ }
1411
+ }
1412
+ return true;
1413
+ };
1414
+ /**
1415
+ * Create a copy of the row.
1416
+ */
1417
+ Row.prototype.copy = function () {
1418
+ var theCopy = new Row(this._constant);
1419
+ theCopy._cellMap = this._cellMap.copy();
1420
+ return theCopy;
1421
+ };
1422
+ /**
1423
+ * Add a constant value to the row constant.
1424
+ *
1425
+ * Returns the new value of the constant.
1426
+ */
1427
+ Row.prototype.add = function (value) {
1428
+ return this._constant += value;
1429
+ };
1430
+ /**
1431
+ * Insert the symbol into the row with the given coefficient.
1432
+ *
1433
+ * If the symbol already exists in the row, the coefficient
1434
+ * will be added to the existing coefficient. If the resulting
1435
+ * coefficient is zero, the symbol will be removed from the row.
1436
+ */
1437
+ Row.prototype.insertSymbol = function (symbol, coefficient) {
1438
+ if (coefficient === void 0) { coefficient = 1.0; }
1439
+ var pair = this._cellMap.setDefault(symbol, function () { return 0.0; });
1440
+ if (nearZero(pair.second += coefficient)) {
1441
+ this._cellMap.erase(symbol);
1442
+ }
1443
+ };
1444
+ /**
1445
+ * Insert a row into this row with a given coefficient.
1446
+ *
1447
+ * The constant and the cells of the other row will be
1448
+ * multiplied by the coefficient and added to this row. Any
1449
+ * cell with a resulting coefficient of zero will be removed
1450
+ * from the row.
1451
+ */
1452
+ Row.prototype.insertRow = function (other, coefficient) {
1453
+ if (coefficient === void 0) { coefficient = 1.0; }
1454
+ this._constant += other._constant * coefficient;
1455
+ var cells = other._cellMap;
1456
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1457
+ var pair = cells.itemAt(i);
1458
+ this.insertSymbol(pair.first, pair.second * coefficient);
1459
+ }
1460
+ };
1461
+ /**
1462
+ * Remove a symbol from the row.
1463
+ */
1464
+ Row.prototype.removeSymbol = function (symbol) {
1465
+ this._cellMap.erase(symbol);
1466
+ };
1467
+ /**
1468
+ * Reverse the sign of the constant and cells in the row.
1469
+ */
1470
+ Row.prototype.reverseSign = function () {
1471
+ this._constant = -this._constant;
1472
+ var cells = this._cellMap;
1473
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1474
+ var pair = cells.itemAt(i);
1475
+ pair.second = -pair.second;
1476
+ }
1477
+ };
1478
+ /**
1479
+ * Solve the row for the given symbol.
1480
+ *
1481
+ * This method assumes the row is of the form
1482
+ * a * x + b * y + c = 0 and (assuming solve for x) will modify
1483
+ * the row to represent the right hand side of
1484
+ * x = -b/a * y - c / a. The target symbol will be removed from
1485
+ * the row, and the constant and other cells will be multiplied
1486
+ * by the negative inverse of the target coefficient.
1487
+ *
1488
+ * The given symbol *must* exist in the row.
1489
+ */
1490
+ Row.prototype.solveFor = function (symbol) {
1491
+ var cells = this._cellMap;
1492
+ var pair = cells.erase(symbol);
1493
+ var coeff = -1 / pair.second;
1494
+ this._constant *= coeff;
1495
+ for (var i = 0, n = cells.size(); i < n; ++i) {
1496
+ cells.itemAt(i).second *= coeff;
1497
+ }
1498
+ };
1499
+ /**
1500
+ * Solve the row for the given symbols.
1501
+ *
1502
+ * This method assumes the row is of the form
1503
+ * x = b * y + c and will solve the row such that
1504
+ * y = x / b - c / b. The rhs symbol will be removed from the
1505
+ * row, the lhs added, and the result divided by the negative
1506
+ * inverse of the rhs coefficient.
1507
+ *
1508
+ * The lhs symbol *must not* exist in the row, and the rhs
1509
+ * symbol must* exist in the row.
1510
+ */
1511
+ Row.prototype.solveForEx = function (lhs, rhs) {
1512
+ this.insertSymbol(lhs, -1);
1513
+ this.solveFor(rhs);
1514
+ };
1515
+ /**
1516
+ * Returns the coefficient for the given symbol.
1517
+ */
1518
+ Row.prototype.coefficientFor = function (symbol) {
1519
+ var pair = this._cellMap.find(symbol);
1520
+ return pair !== undefined ? pair.second : 0.0;
1521
+ };
1522
+ /**
1523
+ * Substitute a symbol with the data from another row.
1524
+ *
1525
+ * Given a row of the form a * x + b and a substitution of the
1526
+ * form x = 3 * y + c the row will be updated to reflect the
1527
+ * expression 3 * a * y + a * c + b.
1528
+ *
1529
+ * If the symbol does not exist in the row, this is a no-op.
1530
+ */
1531
+ Row.prototype.substitute = function (symbol, row) {
1532
+ var pair = this._cellMap.erase(symbol);
1533
+ if (pair !== undefined) {
1534
+ this.insertRow(row, pair.second);
1535
+ }
1536
+ };
1537
+ return Row;
1538
+ }());
1539
+
1540
+ const xSymbol = Symbol("xSymbol");
1541
+ const ySymbol = Symbol("ySymbol");
1542
+ const widthSymbol = Symbol("widthSymbol");
1543
+ const heightSymbol = Symbol("heightSymbol");
1544
+ const addUIElementSymbol = Symbol("addUIElementSymbol");
1545
+ const removeUIElementSymbol = Symbol("removeUIElementSymbol");
1546
+ const addUIConstraintSymbol = Symbol("addConstraintSymbol");
1547
+ const removeUIConstraintSymbol = Symbol("removeUIConstraintSymbol");
1548
+ const addConstraintSymbol = Symbol("addConstraintSymbol");
1549
+ const removeConstraintSymbol = Symbol("removeConstraintSymbol");
1550
+ const addVariableSymbol = Symbol("addVariableSymbol");
1551
+ const removeVariableSymbol = Symbol("removeVariableSymbol");
1552
+ const suggestVariableSymbol = Symbol("suggestVariableSymbol");
1553
+ const disableConstraintSymbol = Symbol("disableConstraintSymbol");
1554
+ const enableConstraintSymbol = Symbol("enableConstraintSymbol");
1555
+ const needsRecalculation = Symbol("needsRecalculation");
1556
+ const flushTransformSymbol = Symbol("flushTransformSymbol");
1557
+ const clickSymbol = Symbol("clickSymbol");
1558
+ const materialSymbol = Symbol("materialSymbol");
1559
+
1560
+ var UIOrientation;
1561
+ (function (UIOrientation) {
1562
+ UIOrientation[UIOrientation["LANDSCAPE"] = 0] = "LANDSCAPE";
1563
+ UIOrientation[UIOrientation["PORTRAIT"] = 1] = "PORTRAIT";
1564
+ UIOrientation[UIOrientation["ALWAYS"] = 2] = "ALWAYS";
1565
+ })(UIOrientation || (UIOrientation = {}));
1566
+ function isUIOrientation(obj) {
1567
+ return obj !== null && Object.values(UIOrientation).some((v) => v === obj);
1568
+ }
1569
+ function resolveOrientation(orientation) {
1570
+ return orientation !== null && orientation !== void 0 ? orientation : UIOrientation.ALWAYS;
1571
+ }
1572
+
1573
+ class UIConstraint {
1574
+ constructor(layer, elements) {
1575
+ this.layer = layer;
1576
+ this.layer[addUIConstraintSymbol](this, elements);
1577
+ }
1578
+ destroy() {
1579
+ this.layer[removeUIConstraintSymbol](this);
1580
+ }
1581
+ }
1582
+
1583
+ var UIConstraintPower;
1584
+ (function (UIConstraintPower) {
1585
+ UIConstraintPower[UIConstraintPower["P0"] = 0] = "P0";
1586
+ UIConstraintPower[UIConstraintPower["P1"] = 1] = "P1";
1587
+ UIConstraintPower[UIConstraintPower["P2"] = 2] = "P2";
1588
+ UIConstraintPower[UIConstraintPower["P3"] = 3] = "P3";
1589
+ UIConstraintPower[UIConstraintPower["P4"] = 4] = "P4";
1590
+ UIConstraintPower[UIConstraintPower["P5"] = 5] = "P5";
1591
+ UIConstraintPower[UIConstraintPower["P6"] = 6] = "P6";
1592
+ UIConstraintPower[UIConstraintPower["P7"] = 7] = "P7";
1593
+ })(UIConstraintPower || (UIConstraintPower = {}));
1594
+ function isUIConstraintPower(obj) {
1595
+ return (obj !== null && Object.values(UIConstraintPower).some((v) => v === obj));
1596
+ }
1597
+ function resolvePower(power) {
1598
+ return power !== null && power !== void 0 ? power : UIConstraintPower.P0;
1599
+ }
1600
+ function convertPowerToStrength(power) {
1601
+ switch (power) {
1602
+ case UIConstraintPower.P0:
1603
+ return Strength.create(1000, 1000, 1000);
1604
+ case UIConstraintPower.P1:
1605
+ return Strength.create(100, 0, 0);
1606
+ case UIConstraintPower.P2:
1607
+ return Strength.create(10, 0, 0);
1608
+ case UIConstraintPower.P3:
1609
+ return Strength.create(0, 100, 0);
1610
+ case UIConstraintPower.P4:
1611
+ return Strength.create(0, 10, 0);
1612
+ case UIConstraintPower.P5:
1613
+ return Strength.create(0, 0, 100);
1614
+ case UIConstraintPower.P6:
1615
+ return Strength.create(0, 0, 10);
1616
+ case UIConstraintPower.P7:
1617
+ return Strength.create(0, 0, 1);
1618
+ default:
1619
+ return Strength.create(1000, 1000, 1000);
1620
+ }
1621
+ }
1622
+
1623
+ var UIConstraintRule;
1624
+ (function (UIConstraintRule) {
1625
+ UIConstraintRule[UIConstraintRule["EQUAL"] = 2] = "EQUAL";
1626
+ UIConstraintRule[UIConstraintRule["LESS"] = 0] = "LESS";
1627
+ UIConstraintRule[UIConstraintRule["GREATER"] = 1] = "GREATER";
1628
+ })(UIConstraintRule || (UIConstraintRule = {}));
1629
+ function isUIConstraintRule(obj) {
1630
+ return obj !== null && Object.values(UIConstraintRule).some((v) => v === obj);
1631
+ }
1632
+ function resolveRule(rule) {
1633
+ return rule !== null && rule !== void 0 ? rule : UIConstraintRule.EQUAL;
1634
+ }
1635
+ function convertRuleToOperator(rule) {
1636
+ switch (rule) {
1637
+ case UIConstraintRule.EQUAL:
1638
+ return Operator.Eq;
1639
+ case UIConstraintRule.LESS:
1640
+ return Operator.Le;
1641
+ case UIConstraintRule.GREATER:
1642
+ return Operator.Ge;
1643
+ default:
1644
+ return Operator.Eq;
1645
+ }
1646
+ }
1647
+
1648
+ class UIHeightConstraint extends UIConstraint {
1649
+ constructor(element, parameters) {
1650
+ var _a;
1651
+ super(element.layer, new Set([element]));
1652
+ this.element = element;
1653
+ this.parameters = {
1654
+ height: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.height) !== null && _a !== void 0 ? _a : 100,
1655
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
1656
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
1657
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
1658
+ };
1659
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
1660
+ this.parameters.orientation === this.layer.orientation) {
1661
+ this.buildConstraints();
1662
+ }
1663
+ }
1664
+ destroy() {
1665
+ this.destroyConstraints();
1666
+ super.destroy();
1667
+ }
1668
+ [disableConstraintSymbol](orientation) {
1669
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
1670
+ orientation !== this.parameters.orientation) {
1671
+ this.destroyConstraints();
1672
+ }
1673
+ }
1674
+ [enableConstraintSymbol](orientation) {
1675
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
1676
+ orientation === this.parameters.orientation) {
1677
+ this.buildConstraints();
1678
+ }
1679
+ }
1680
+ buildConstraints() {
1681
+ this.constraint = new Constraint(new Expression(this.element[heightSymbol]), convertRuleToOperator(this.parameters.rule), this.parameters.height, convertPowerToStrength(this.parameters.power));
1682
+ this.layer[addConstraintSymbol](this, this.constraint);
1683
+ }
1684
+ destroyConstraints() {
1685
+ if (this.constraint) {
1686
+ this.layer[removeConstraintSymbol](this, this.constraint);
1687
+ this.constraint = undefined;
1688
+ }
1689
+ }
1690
+ }
1691
+
1692
+ /**
1693
+ * Default priority value for event listeners.
1694
+ * Lower values indicate higher priority.
1695
+ */
1696
+ const DEFAULT_PRIORITY = 100;
1697
+ /**
1698
+ * A priority-based event emitter implementation.
1699
+ * The name "Eventail" is a combination of "event" + "tail", reflecting its queue-like nature.
1700
+ *
1701
+ * Features:
1702
+ * - Priority-based event listeners
1703
+ * - Context binding support
1704
+ * - One-time event listeners
1705
+ * - Type-safe event handling
1706
+ *
1707
+ * @example
1708
+ * ```typescript
1709
+ * const emitter = new Eventail();
1710
+ *
1711
+ * // Regular event listener
1712
+ * emitter.on('event', (data) => console.log(data));
1713
+ *
1714
+ * // One-time event listener with high priority
1715
+ * emitter.once('event', callback, context, 50);
1716
+ *
1717
+ * // Remove specific listener
1718
+ * emitter.off('event', callback);
1719
+ * ```
1720
+ */
1721
+ class Eventail {
1722
+ constructor() {
1723
+ /** Map storing event listeners for each event type */
1724
+ this.listeners = new Map();
1725
+ }
1726
+ /**
1727
+ * Adds an event listener for the specified event type.
1728
+ *
1729
+ * @param type - The event type to listen for
1730
+ * @param callback - The function to be called when the event is emitted
1731
+ * @param context - Optional this context for the callback
1732
+ * @param priority - Optional priority value (lower = higher priority)
1733
+ * @returns The emitter instance for chaining
1734
+ *
1735
+ * @example
1736
+ * ```typescript
1737
+ * emitter.on('data', (value) => console.log(value));
1738
+ * emitter.on('error', handleError, this, 50);
1739
+ * ```
1740
+ */
1741
+ on(type, callback, context, priority = DEFAULT_PRIORITY) {
1742
+ this.addListener(type, callback, context, priority, false);
1743
+ return this;
1744
+ }
1745
+ /**
1746
+ * Adds a one-time event listener that will be removed after first execution.
1747
+ *
1748
+ * @param type - The event type to listen for
1749
+ * @param callback - The function to be called when the event is emitted
1750
+ * @param context - Optional this context for the callback
1751
+ * @param priority - Optional priority value (lower = higher priority)
1752
+ * @returns The emitter instance for chaining
1753
+ *
1754
+ * @example
1755
+ * ```typescript
1756
+ * emitter.once('init', () => console.log('Initialized'));
1757
+ * ```
1758
+ */
1759
+ once(type, callback, context, priority = DEFAULT_PRIORITY) {
1760
+ this.addListener(type, callback, context, priority, true);
1761
+ return this;
1762
+ }
1763
+ /**
1764
+ * Removes event listener(s) from the specified event type.
1765
+ *
1766
+ * @param type - The event type to remove listener(s) from
1767
+ * @param callback - Optional callback to remove specific listener
1768
+ * @param context - Optional context to match when removing
1769
+ * @returns The emitter instance for chaining
1770
+ *
1771
+ * @example
1772
+ * ```typescript
1773
+ * // Remove all listeners for 'data' event
1774
+ * emitter.off('data');
1775
+ *
1776
+ * // Remove specific listener
1777
+ * emitter.off('data', callback);
1778
+ *
1779
+ * // Remove listener with specific context
1780
+ * emitter.off('data', callback, context);
1781
+ * ```
1782
+ */
1783
+ off(type, callback, context) {
1784
+ const current = this.listeners.get(type);
1785
+ if (!current) {
1786
+ return this;
1787
+ }
1788
+ if (!callback) {
1789
+ this.listeners.delete(type);
1790
+ return this;
1791
+ }
1792
+ const filtered = current.filter((l) => l.callback !== callback ||
1793
+ (context !== undefined && l.context !== context));
1794
+ filtered.length
1795
+ ? this.listeners.set(type, filtered)
1796
+ : this.listeners.delete(type);
1797
+ return this;
1798
+ }
1799
+ /**
1800
+ * Emits an event, triggering all registered listeners in priority order.
1801
+ * Protected method to allow extension in derived classes.
1802
+ *
1803
+ * @param type - The event type to emit
1804
+ * @param args - Arguments to pass to the listeners
1805
+ * @returns Boolean indicating if the event had listeners
1806
+ *
1807
+ * @example
1808
+ * ```typescript
1809
+ * class MyEmitter extends Eventail {
1810
+ * public trigger(type: string, ...args: unknown[]) {
1811
+ * return this.emit(type, ...args);
1812
+ * }
1813
+ * }
1814
+ * ```
1815
+ */
1816
+ emit(type, ...args) {
1817
+ const current = this.listeners.get(type);
1818
+ if (!(current === null || current === void 0 ? void 0 : current.length)) {
1819
+ return false;
1820
+ }
1821
+ for (const listener of [...current]) {
1822
+ listener.callback.apply(listener.context, args);
1823
+ if (listener.once) {
1824
+ this.off(type, listener.callback, listener.context);
1825
+ }
1826
+ }
1827
+ return true;
1828
+ }
1829
+ /**
1830
+ * Internal method to add a new event listener with the specified configuration.
1831
+ * Maintains priority order and prevents duplicate listeners.
1832
+ *
1833
+ * @param type - Event type
1834
+ * @param callback - Event callback
1835
+ * @param context - Callback context
1836
+ * @param priority - Event priority
1837
+ * @param once - Whether it's a one-time listener
1838
+ * @throws {Error} If the listener already exists
1839
+ */
1840
+ addListener(type, callback, context, priority, once) {
1841
+ let list = this.listeners.get(type);
1842
+ if (!list) {
1843
+ list = [];
1844
+ this.listeners.set(type, list);
1845
+ }
1846
+ if (list.some((l) => l.callback === callback && l.context === context)) {
1847
+ throw new Error("Event listener already exists");
1848
+ }
1849
+ const event = { callback, context, priority, once };
1850
+ let i = 0;
1851
+ while (i < list.length && list[i].priority <= priority) {
1852
+ i++;
1853
+ }
1854
+ list.splice(i, 0, event);
1855
+ }
1856
+ }
1857
+
1858
+ const tempVector2 = new Vector2();
1859
+ const tempBox2 = new Box2();
1860
+ function testElement(elementX, elementY, elementWidth, elementHeight, xClick, yClick) {
1861
+ tempVector2.set(xClick, yClick);
1862
+ tempBox2.min.set(elementX, elementY);
1863
+ tempBox2.max.set(elementWidth, elementHeight).add(tempBox2.min);
1864
+ return tempBox2.containsPoint(tempVector2);
1865
+ }
1866
+
1867
+ function applyMicroTransformations(object, micro, x, y, width, height) {
1868
+ const anchorOffsetX = width * micro.anchorX;
1869
+ const anchorOffsetY = height * micro.anchorY;
1870
+ const centerX = x + anchorOffsetX;
1871
+ const centerY = y + anchorOffsetY;
1872
+ let localX = x - centerX;
1873
+ let localY = y - centerY;
1874
+ localX *= micro.scaleX;
1875
+ localY *= micro.scaleY;
1876
+ const cos = Math.cos(micro.rotation);
1877
+ const sin = Math.sin(micro.rotation);
1878
+ localX = localX * cos - localY * sin;
1879
+ localY = localX * sin + localY * cos;
1880
+ localX += micro.x;
1881
+ localY += micro.y;
1882
+ object.position.x = localX + centerX;
1883
+ object.position.y = localY + centerY;
1884
+ object.rotation.z = micro.rotation;
1885
+ object.scale.x = width * micro.scaleX;
1886
+ object.scale.y = height * micro.scaleY;
1887
+ }
1888
+ // function rotatePoint(
1889
+ // x: number,
1890
+ // y: number,
1891
+ // anchorX: number,
1892
+ // anchorY: number,
1893
+ // rotation: number,
1894
+ // ): { x: number; y: number } {
1895
+ // const cos = Math.cos(rotation);
1896
+ // const sin = Math.sin(rotation);
1897
+ // const dx = x - anchorX;
1898
+ // const dy = y - anchorY;
1899
+ // const rotatedX = dx * cos - dy * sin;
1900
+ // const rotatedY = dx * sin + dy * cos;
1901
+ // return {
1902
+ // x: rotatedX + anchorX,
1903
+ // y: rotatedY + anchorY,
1904
+ // };
1905
+ // }
1906
+
1907
+ var UIBehavior;
1908
+ (function (UIBehavior) {
1909
+ UIBehavior[UIBehavior["HIDDEN"] = 0] = "HIDDEN";
1910
+ UIBehavior[UIBehavior["VISIBLE"] = 1] = "VISIBLE";
1911
+ UIBehavior[UIBehavior["INTERACTIVE"] = 2] = "INTERACTIVE";
1912
+ })(UIBehavior || (UIBehavior = {}));
1913
+
1914
+ var _a$2;
1915
+ const DEFAULT_POSITION = 0;
1916
+ const DEFAULT_ANCHOR = 0.5;
1917
+ const DEFAULT_SCALE = 1;
1918
+ const DEFAULT_ROTATION = 0;
1919
+ class UIMicroTransformations {
1920
+ constructor() {
1921
+ this[_a$2] = false;
1922
+ this.positionXInternal = DEFAULT_POSITION;
1923
+ this.positionYInternal = DEFAULT_POSITION;
1924
+ this.anchorXInternal = DEFAULT_ANCHOR;
1925
+ this.anchorYInternal = DEFAULT_ANCHOR;
1926
+ this.scaleXInternal = DEFAULT_SCALE;
1927
+ this.scaleYInternal = DEFAULT_SCALE;
1928
+ this.rotationInternal = DEFAULT_ROTATION;
1929
+ }
1930
+ get x() {
1931
+ return this.positionXInternal;
1932
+ }
1933
+ get y() {
1934
+ return this.positionYInternal;
1935
+ }
1936
+ get anchorX() {
1937
+ return this.anchorXInternal;
1938
+ }
1939
+ get anchorY() {
1940
+ return this.anchorYInternal;
1941
+ }
1942
+ get scaleX() {
1943
+ return this.scaleXInternal;
1944
+ }
1945
+ get scaleY() {
1946
+ return this.scaleYInternal;
1947
+ }
1948
+ get angle() {
1949
+ return MathUtils.radToDeg(this.rotationInternal);
1950
+ }
1951
+ get rotation() {
1952
+ return this.rotationInternal;
1953
+ }
1954
+ set x(value) {
1955
+ this.positionXInternal = value;
1956
+ this[needsRecalculation] = true;
1957
+ }
1958
+ set y(value) {
1959
+ this.positionYInternal = value;
1960
+ this[needsRecalculation] = true;
1961
+ }
1962
+ set anchorX(value) {
1963
+ this.anchorXInternal = value;
1964
+ this[needsRecalculation] = true;
1965
+ }
1966
+ set anchorY(value) {
1967
+ this.anchorYInternal = value;
1968
+ this[needsRecalculation] = true;
1969
+ }
1970
+ set scaleX(value) {
1971
+ this.scaleXInternal = value;
1972
+ this[needsRecalculation] = true;
1973
+ }
1974
+ set scaleY(value) {
1975
+ this.scaleYInternal = value;
1976
+ this[needsRecalculation] = true;
1977
+ }
1978
+ set angle(value) {
1979
+ this.rotationInternal = MathUtils.degToRad(value);
1980
+ this[needsRecalculation] = true;
1981
+ }
1982
+ set rotation(value) {
1983
+ this.rotationInternal = value;
1984
+ this[needsRecalculation] = true;
1985
+ }
1986
+ reset() {
1987
+ this.positionXInternal = DEFAULT_POSITION;
1988
+ this.positionYInternal = DEFAULT_POSITION;
1989
+ this.anchorXInternal = DEFAULT_ANCHOR;
1990
+ this.anchorYInternal = DEFAULT_ANCHOR;
1991
+ this.scaleXInternal = DEFAULT_SCALE;
1992
+ this.scaleYInternal = DEFAULT_SCALE;
1993
+ this.rotationInternal = DEFAULT_ROTATION;
1994
+ this[needsRecalculation] = true;
1995
+ }
1996
+ }
1997
+ _a$2 = needsRecalculation;
1998
+
1999
+ var _a$1, _b$1, _c$1, _d$1, _e;
2000
+ var UIElementEvent;
2001
+ (function (UIElementEvent) {
2002
+ UIElementEvent["CLICK"] = "click";
2003
+ })(UIElementEvent || (UIElementEvent = {}));
2004
+ class UIElement extends Eventail {
2005
+ constructor(layer, object, x, y, width, height) {
2006
+ super();
2007
+ this.layer = layer;
2008
+ this.object = object;
2009
+ this.micro = new UIMicroTransformations();
2010
+ this[_a$1] = new Variable("x");
2011
+ this[_b$1] = new Variable("y");
2012
+ this[_c$1] = new Variable("width");
2013
+ this[_d$1] = new Variable("height");
2014
+ this[_e] = false;
2015
+ this.behaviorInternal = UIBehavior.VISIBLE;
2016
+ this.layer[addUIElementSymbol](this, this.object);
2017
+ this.layer[addVariableSymbol](this, this[xSymbol], convertPowerToStrength(UIConstraintPower.P7));
2018
+ this.layer[addVariableSymbol](this, this[ySymbol], convertPowerToStrength(UIConstraintPower.P7));
2019
+ this.layer[addVariableSymbol](this, this[widthSymbol], convertPowerToStrength(UIConstraintPower.P5));
2020
+ this.layer[addVariableSymbol](this, this[heightSymbol], convertPowerToStrength(UIConstraintPower.P5));
2021
+ this[xSymbol].setValue(x);
2022
+ this[ySymbol].setValue(y);
2023
+ this[widthSymbol].setValue(width);
2024
+ this[heightSymbol].setValue(height);
2025
+ this.layer[suggestVariableSymbol](this, this[xSymbol], x);
2026
+ this.layer[suggestVariableSymbol](this, this[ySymbol], y);
2027
+ this.layer[suggestVariableSymbol](this, this[widthSymbol], width);
2028
+ this.layer[suggestVariableSymbol](this, this[heightSymbol], height);
2029
+ }
2030
+ get x() {
2031
+ return this[xSymbol].value();
2032
+ }
2033
+ get y() {
2034
+ return this[ySymbol].value();
2035
+ }
2036
+ get width() {
2037
+ return this[widthSymbol].value();
2038
+ }
2039
+ get height() {
2040
+ return this[heightSymbol].value();
2041
+ }
2042
+ get zIndex() {
2043
+ return this.object.position.z;
2044
+ }
2045
+ get behavior() {
2046
+ return this.behaviorInternal;
2047
+ }
2048
+ set x(value) {
2049
+ this.layer[suggestVariableSymbol](this, this[xSymbol], value);
2050
+ }
2051
+ set y(value) {
2052
+ this.layer[suggestVariableSymbol](this, this[ySymbol], value);
2053
+ }
2054
+ set width(value) {
2055
+ this.layer[suggestVariableSymbol](this, this[widthSymbol], value);
2056
+ }
2057
+ set height(value) {
2058
+ this.layer[suggestVariableSymbol](this, this[heightSymbol], value);
2059
+ }
2060
+ set zIndex(value) {
2061
+ this.object.position.z = value;
2062
+ }
2063
+ set behavior(value) {
2064
+ this.behaviorInternal = value;
2065
+ this.object.visible = value !== UIBehavior.HIDDEN;
2066
+ }
2067
+ destroy() {
2068
+ this.layer[removeVariableSymbol](this, this[xSymbol]);
2069
+ this.layer[removeVariableSymbol](this, this[ySymbol]);
2070
+ this.layer[removeVariableSymbol](this, this[widthSymbol]);
2071
+ this.layer[removeVariableSymbol](this, this[heightSymbol]);
2072
+ this.layer[removeUIElementSymbol](this);
2073
+ }
2074
+ [(_a$1 = xSymbol, _b$1 = ySymbol, _c$1 = widthSymbol, _d$1 = heightSymbol, _e = needsRecalculation, flushTransformSymbol)]() {
2075
+ if (this[needsRecalculation] || this.micro[needsRecalculation]) {
2076
+ applyMicroTransformations(this.object, this.micro, this.x, this.y, this.width, this.height);
2077
+ this[needsRecalculation] = false;
2078
+ this.micro[needsRecalculation] = false;
2079
+ }
2080
+ }
2081
+ [clickSymbol](x, y) {
2082
+ if (this.behavior !== UIBehavior.INTERACTIVE) {
2083
+ return false;
2084
+ }
2085
+ this[flushTransformSymbol]();
2086
+ if (testElement(this.x, this.y, this.width, this.height, x, y)) {
2087
+ this.emit(UIElementEvent.CLICK, this);
2088
+ return true;
2089
+ }
2090
+ return false;
2091
+ }
2092
+ }
2093
+
2094
+ var _a, _b, _c, _d;
2095
+ class UILayer {
2096
+ constructor() {
2097
+ this.behavior = UIBehavior.VISIBLE;
2098
+ this[_a] = new Variable();
2099
+ this[_b] = new Variable();
2100
+ this[_c] = new Variable();
2101
+ this[_d] = new Variable();
2102
+ this.scene = new Scene();
2103
+ this.camera = new OrthographicCamera();
2104
+ this.solver = new Solver();
2105
+ this.elements = new Map();
2106
+ this.constraints = new Map();
2107
+ this.orientationPrivate = UIOrientation.PORTRAIT;
2108
+ this.needsRecalculation = false;
2109
+ }
2110
+ get orientation() {
2111
+ return this.orientationPrivate;
2112
+ }
2113
+ destroy() {
2114
+ this.solver = undefined;
2115
+ for (const constraint of this.constraints.keys()) {
2116
+ constraint.destroy();
2117
+ }
2118
+ for (const element of this.elements.keys()) {
2119
+ element.destroy();
2120
+ }
2121
+ }
2122
+ [(_a = xSymbol, _b = ySymbol, _c = widthSymbol, _d = heightSymbol, addUIElementSymbol)](element, object) {
2123
+ if (this.elements.has(element)) {
2124
+ throw new Error("Element already added");
2125
+ }
2126
+ this.elements.set(element, {
2127
+ object,
2128
+ variables: new Map(),
2129
+ constraints: new Set(),
2130
+ });
2131
+ this.scene.add(object);
2132
+ }
2133
+ [removeUIElementSymbol](element) {
2134
+ const dependencies = this.elements.get(element);
2135
+ if (dependencies === undefined) {
2136
+ throw new Error("Element not found");
2137
+ }
2138
+ if (dependencies.variables.size > 0) {
2139
+ throw new Error("Variables should be removed before removing element");
2140
+ }
2141
+ if (dependencies.constraints.size > 0) {
2142
+ throw new Error("Constraints should be removed before removing element");
2143
+ }
2144
+ this.elements.delete(element);
2145
+ this.scene.remove(dependencies.object);
2146
+ }
2147
+ [addUIConstraintSymbol](constraint, elements) {
2148
+ if (this.constraints.has(constraint)) {
2149
+ throw new Error("Constraint already added");
2150
+ }
2151
+ for (const element of elements) {
2152
+ const dependencies = this.elements.get(element);
2153
+ if (dependencies === undefined) {
2154
+ throw new Error("Element not found");
2155
+ }
2156
+ if (dependencies.constraints.has(constraint)) {
2157
+ throw new Error("Something went wrong");
2158
+ }
2159
+ dependencies.constraints.add(constraint);
2160
+ }
2161
+ this.constraints.set(constraint, {
2162
+ elements,
2163
+ variables: new Map(),
2164
+ constraints: new Set(),
2165
+ });
2166
+ }
2167
+ [removeUIConstraintSymbol](constraint) {
2168
+ const dependencies = this.constraints.get(constraint);
2169
+ if (dependencies === undefined) {
2170
+ throw new Error("Constraint not found");
2171
+ }
2172
+ if (dependencies.variables.size > 0) {
2173
+ throw new Error("Variables should be removed before removing constraint");
2174
+ }
2175
+ if (dependencies.constraints.size > 0) {
2176
+ throw new Error("Constraints should be removed before removing constraint");
2177
+ }
2178
+ for (const element of dependencies.elements) {
2179
+ const dependencies = this.elements.get(element);
2180
+ if (dependencies === undefined) {
2181
+ throw new Error("Element not found");
2182
+ }
2183
+ if (!dependencies.constraints.has(constraint)) {
2184
+ throw new Error("Something went wrong");
2185
+ }
2186
+ dependencies.constraints.delete(constraint);
2187
+ }
2188
+ this.constraints.delete(constraint);
2189
+ }
2190
+ [addConstraintSymbol](owner, constraint) {
2191
+ var _e;
2192
+ const dependencies = this.constraints.get(owner);
2193
+ if (dependencies === undefined) {
2194
+ throw new Error("Before adding constraint you need to add it's owner");
2195
+ }
2196
+ if (dependencies.constraints.has(constraint)) {
2197
+ throw new Error("Constraint already exists");
2198
+ }
2199
+ dependencies.constraints.add(constraint);
2200
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.addConstraint(constraint);
2201
+ this.needsRecalculation = true;
2202
+ }
2203
+ [removeConstraintSymbol](owner, constraint) {
2204
+ var _e;
2205
+ const dependencies = this.constraints.get(owner);
2206
+ if (dependencies === undefined) {
2207
+ throw new Error("Before removing constraint you need to add it's owner");
2208
+ }
2209
+ if (!dependencies.constraints.has(constraint)) {
2210
+ throw new Error("Constraint not found");
2211
+ }
2212
+ dependencies.constraints.delete(constraint);
2213
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.removeConstraint(constraint);
2214
+ this.needsRecalculation = true;
2215
+ }
2216
+ [addVariableSymbol](owner, variable, strength) {
2217
+ var _e;
2218
+ const dependencies = owner instanceof UIElement
2219
+ ? this.elements.get(owner)
2220
+ : this.constraints.get(owner);
2221
+ if (dependencies === undefined) {
2222
+ throw new Error("Before adding variable you need to add it's owner");
2223
+ }
2224
+ if (dependencies.variables.has(variable)) {
2225
+ throw new Error("Variable already exists");
2226
+ }
2227
+ dependencies.variables.set(variable, {
2228
+ strength,
2229
+ suggestedValue: variable.value(),
2230
+ });
2231
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.addEditVariable(variable, strength);
2232
+ }
2233
+ [removeVariableSymbol](owner, variable) {
2234
+ var _e;
2235
+ const dependencies = owner instanceof UIElement
2236
+ ? this.elements.get(owner)
2237
+ : this.constraints.get(owner);
2238
+ if (dependencies === undefined) {
2239
+ throw new Error("Before removing variable you need to add it's owner");
2240
+ }
2241
+ if (!dependencies.variables.has(variable)) {
2242
+ throw new Error("Variable does not exist");
2243
+ }
2244
+ dependencies.variables.delete(variable);
2245
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.removeEditVariable(variable);
2246
+ }
2247
+ [suggestVariableSymbol](owner, variable, value) {
2248
+ var _e;
2249
+ const dependencies = owner instanceof UIElement
2250
+ ? this.elements.get(owner)
2251
+ : this.constraints.get(owner);
2252
+ if (dependencies === undefined) {
2253
+ throw new Error("Before suggesting variable you need to add it's owner");
2254
+ }
2255
+ const description = dependencies.variables.get(variable);
2256
+ if (!description) {
2257
+ throw new Error("Variable does not exist");
2258
+ }
2259
+ if (description.suggestedValue !== value) {
2260
+ description.suggestedValue = value;
2261
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.suggestValue(variable, value);
2262
+ this.needsRecalculation = true;
2263
+ }
2264
+ }
2265
+ render(renderer) {
2266
+ var _e;
2267
+ if (this.behavior === UIBehavior.HIDDEN) {
2268
+ return;
2269
+ }
2270
+ if (this.needsRecalculation) {
2271
+ this.needsRecalculation = false;
2272
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.updateVariables();
2273
+ for (const element of this.elements.keys()) {
2274
+ element[needsRecalculation] = true;
2275
+ }
2276
+ }
2277
+ for (const element of this.elements.keys()) {
2278
+ element[needsRecalculation] = true;
2279
+ }
2280
+ for (const element of this.elements.keys()) {
2281
+ element[flushTransformSymbol]();
2282
+ }
2283
+ renderer.render(this.scene, this.camera);
2284
+ }
2285
+ clickInternal(x, y) {
2286
+ if (this.behavior !== UIBehavior.INTERACTIVE) {
2287
+ return;
2288
+ }
2289
+ const elements = [...this.elements.keys()]
2290
+ .filter((e) => e.behavior === UIBehavior.INTERACTIVE)
2291
+ .sort((a, b) => a.zIndex - b.zIndex);
2292
+ for (const element of elements) {
2293
+ if (element[clickSymbol](x, y)) {
2294
+ break;
2295
+ }
2296
+ }
2297
+ }
2298
+ resizeInternal(width, height) {
2299
+ this.applyCameraSize(width, height);
2300
+ this.rebuildLayerConstraints(width, height);
2301
+ this.updateOrientation(width, height);
2302
+ this.needsRecalculation = true;
2303
+ }
2304
+ applyCameraSize(width, height) {
2305
+ this.camera.near = -1e3;
2306
+ this.camera.far = 0;
2307
+ this.camera.bottom = 0;
2308
+ this.camera.left = 0;
2309
+ this.camera.right = width;
2310
+ this.camera.top = height;
2311
+ this.camera.updateProjectionMatrix();
2312
+ }
2313
+ rebuildLayerConstraints(width, height) {
2314
+ var _e, _f, _g, _h, _j, _k, _l, _m;
2315
+ if (this.constraintX) {
2316
+ (_e = this.solver) === null || _e === void 0 ? void 0 : _e.removeConstraint(this.constraintX);
2317
+ this.constraintX = undefined;
2318
+ }
2319
+ if (this.constraintY) {
2320
+ (_f = this.solver) === null || _f === void 0 ? void 0 : _f.removeConstraint(this.constraintY);
2321
+ this.constraintY = undefined;
2322
+ }
2323
+ if (this.constraintW) {
2324
+ (_g = this.solver) === null || _g === void 0 ? void 0 : _g.removeConstraint(this.constraintW);
2325
+ this.constraintW = undefined;
2326
+ }
2327
+ if (this.constraintH) {
2328
+ (_h = this.solver) === null || _h === void 0 ? void 0 : _h.removeConstraint(this.constraintH);
2329
+ this.constraintH = undefined;
2330
+ }
2331
+ this.constraintX = new Constraint(new Expression(this[xSymbol]), Operator.Eq, 0, Strength.required);
2332
+ this.constraintY = new Constraint(new Expression(this[ySymbol]), Operator.Eq, 0, Strength.required);
2333
+ this.constraintW = new Constraint(new Expression(this[widthSymbol]), Operator.Eq, width, Strength.required);
2334
+ this.constraintH = new Constraint(new Expression(this[heightSymbol]), Operator.Eq, height, Strength.required);
2335
+ (_j = this.solver) === null || _j === void 0 ? void 0 : _j.addConstraint(this.constraintX);
2336
+ (_k = this.solver) === null || _k === void 0 ? void 0 : _k.addConstraint(this.constraintY);
2337
+ (_l = this.solver) === null || _l === void 0 ? void 0 : _l.addConstraint(this.constraintW);
2338
+ (_m = this.solver) === null || _m === void 0 ? void 0 : _m.addConstraint(this.constraintH);
2339
+ }
2340
+ updateOrientation(width, height) {
2341
+ const lastOrientation = this.orientationPrivate;
2342
+ this.orientationPrivate =
2343
+ width > height ? UIOrientation.LANDSCAPE : UIOrientation.PORTRAIT;
2344
+ if (lastOrientation !== this.orientationPrivate) {
2345
+ this.solver = undefined;
2346
+ for (const constraint of this.constraints.keys()) {
2347
+ constraint[enableConstraintSymbol](this.orientationPrivate);
2348
+ }
2349
+ for (const constraint of this.constraints.keys()) {
2350
+ constraint[disableConstraintSymbol](this.orientationPrivate);
2351
+ }
2352
+ this.solver = new Solver();
2353
+ const descriptions = [
2354
+ ...this.elements.values(),
2355
+ ...this.constraints.values(),
2356
+ ];
2357
+ for (const description of descriptions) {
2358
+ for (const [key, value] of description.variables.entries()) {
2359
+ this.solver.addEditVariable(key, value.strength);
2360
+ this.solver.suggestValue(key, value.suggestedValue);
2361
+ }
2362
+ }
2363
+ if (this.constraintX) {
2364
+ this.solver.addConstraint(this.constraintX);
2365
+ }
2366
+ if (this.constraintY) {
2367
+ this.solver.addConstraint(this.constraintY);
2368
+ }
2369
+ if (this.constraintW) {
2370
+ this.solver.addConstraint(this.constraintW);
2371
+ }
2372
+ if (this.constraintH) {
2373
+ this.solver.addConstraint(this.constraintH);
2374
+ }
2375
+ for (const dependency of this.constraints.values()) {
2376
+ for (const constraint of dependency.constraints.values()) {
2377
+ this.solver.addConstraint(constraint);
2378
+ }
2379
+ }
2380
+ }
2381
+ }
2382
+ }
2383
+
2384
+ function assertSameLayer(elementOne, elementTwo, message) {
2385
+ if ((elementOne instanceof UILayer ? elementOne : elementOne.layer) !==
2386
+ elementTwo.layer) {
2387
+ throw new Error(`Elements must be on the same layer - element "${elementTwo.constructor.name}" cannot interact with elements from a different layer`);
2388
+ }
2389
+ }
2390
+ function assertSize(width, height, message) {
2391
+ if (width <= 0 || height <= 0) {
2392
+ throw new Error(message !== null && message !== void 0 ? message : `Invalid dimensions: width (${width}) and height (${height}) must both be positive numbers greater than 0`);
2393
+ }
2394
+ }
2395
+
2396
+ class UIHorizontalDistanceConstraint extends UIConstraint {
2397
+ constructor(elementOne, elementTwo, parameters) {
2398
+ var _a, _b, _c;
2399
+ assertSameLayer(elementOne, elementTwo);
2400
+ super(elementTwo.layer, new Set(elementOne instanceof UIElement
2401
+ ? [elementOne, elementTwo]
2402
+ : [elementTwo]));
2403
+ this.elementOne = elementOne;
2404
+ this.elementTwo = elementTwo;
2405
+ this.parameters = {
2406
+ anchorOne: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.anchorOne) !== null && _a !== void 0 ? _a : 0.5,
2407
+ anchorTwo: (_b = parameters === null || parameters === void 0 ? void 0 : parameters.anchorTwo) !== null && _b !== void 0 ? _b : 0.5,
2408
+ distance: (_c = parameters === null || parameters === void 0 ? void 0 : parameters.distance) !== null && _c !== void 0 ? _c : 0,
2409
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
2410
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
2411
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2412
+ };
2413
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2414
+ this.parameters.orientation === this.layer.orientation) {
2415
+ this.buildConstraints();
2416
+ }
2417
+ }
2418
+ destroy() {
2419
+ this.destroyConstraints();
2420
+ super.destroy();
2421
+ }
2422
+ [disableConstraintSymbol](orientation) {
2423
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2424
+ orientation !== this.parameters.orientation) {
2425
+ this.destroyConstraints();
2426
+ }
2427
+ }
2428
+ [enableConstraintSymbol](orientation) {
2429
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2430
+ orientation === this.parameters.orientation) {
2431
+ this.buildConstraints();
2432
+ }
2433
+ }
2434
+ buildConstraints() {
2435
+ const expressionOne = new Expression(this.elementOne[xSymbol]).plus(new Expression(this.elementOne[widthSymbol]).multiply(this.parameters.anchorOne));
2436
+ const expressionTwo = new Expression(this.elementTwo[xSymbol]).plus(new Expression(this.elementTwo[widthSymbol]).multiply(this.parameters.anchorTwo));
2437
+ this.constraint = new Constraint(expressionTwo.minus(expressionOne), convertRuleToOperator(this.parameters.rule), this.parameters.distance, convertPowerToStrength(this.parameters.power));
2438
+ this.layer[addConstraintSymbol](this, this.constraint);
2439
+ }
2440
+ destroyConstraints() {
2441
+ if (this.constraint) {
2442
+ this.layer[removeConstraintSymbol](this, this.constraint);
2443
+ this.constraint = undefined;
2444
+ }
2445
+ }
2446
+ }
2447
+
2448
+ class UIHorizontalProportionConstraint extends UIConstraint {
2449
+ constructor(elementOne, elementTwo, parameters) {
2450
+ var _a;
2451
+ assertSameLayer(elementOne, elementTwo);
2452
+ super(elementTwo.layer, new Set(elementOne instanceof UIElement
2453
+ ? [elementOne, elementTwo]
2454
+ : [elementTwo]));
2455
+ this.elementOne = elementOne;
2456
+ this.elementTwo = elementTwo;
2457
+ this.parameters = {
2458
+ proportion: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.proportion) !== null && _a !== void 0 ? _a : 1,
2459
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
2460
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
2461
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2462
+ };
2463
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2464
+ this.parameters.orientation === this.layer.orientation) {
2465
+ this.buildConstraints();
2466
+ }
2467
+ }
2468
+ destroy() {
2469
+ this.destroyConstraints();
2470
+ super.destroy();
2471
+ }
2472
+ [disableConstraintSymbol](orientation) {
2473
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2474
+ orientation !== this.parameters.orientation) {
2475
+ this.destroyConstraints();
2476
+ }
2477
+ }
2478
+ [enableConstraintSymbol](orientation) {
2479
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2480
+ orientation === this.parameters.orientation) {
2481
+ this.buildConstraints();
2482
+ }
2483
+ }
2484
+ buildConstraints() {
2485
+ const expressionOne = new Expression(this.elementOne[widthSymbol]).multiply(this.parameters.proportion);
2486
+ const expressionTwo = new Expression(this.elementTwo[widthSymbol]);
2487
+ this.constraint = new Constraint(expressionOne.minus(expressionTwo), convertRuleToOperator(this.parameters.rule), 0, convertPowerToStrength(this.parameters.power));
2488
+ this.layer[addConstraintSymbol](this, this.constraint);
2489
+ }
2490
+ destroyConstraints() {
2491
+ if (this.constraint) {
2492
+ this.layer[removeConstraintSymbol](this, this.constraint);
2493
+ this.constraint = undefined;
2494
+ }
2495
+ }
2496
+ }
2497
+
2498
+ class UIVerticalDistanceConstraint extends UIConstraint {
2499
+ constructor(elementOne, elementTwo, parameters) {
2500
+ var _a, _b, _c;
2501
+ assertSameLayer(elementOne, elementTwo);
2502
+ super(elementTwo.layer, new Set(elementOne instanceof UIElement
2503
+ ? [elementOne, elementTwo]
2504
+ : [elementTwo]));
2505
+ this.elementOne = elementOne;
2506
+ this.elementTwo = elementTwo;
2507
+ this.parameters = {
2508
+ anchorOne: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.anchorOne) !== null && _a !== void 0 ? _a : 0.5,
2509
+ anchorTwo: (_b = parameters === null || parameters === void 0 ? void 0 : parameters.anchorTwo) !== null && _b !== void 0 ? _b : 0.5,
2510
+ distance: (_c = parameters === null || parameters === void 0 ? void 0 : parameters.distance) !== null && _c !== void 0 ? _c : 0,
2511
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
2512
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
2513
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2514
+ };
2515
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2516
+ this.parameters.orientation === this.layer.orientation) {
2517
+ this.buildConstraints();
2518
+ }
2519
+ }
2520
+ destroy() {
2521
+ this.destroyConstraints();
2522
+ super.destroy();
2523
+ }
2524
+ [disableConstraintSymbol](orientation) {
2525
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2526
+ orientation !== this.parameters.orientation) {
2527
+ this.destroyConstraints();
2528
+ }
2529
+ }
2530
+ [enableConstraintSymbol](orientation) {
2531
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2532
+ orientation === this.parameters.orientation) {
2533
+ this.buildConstraints();
2534
+ }
2535
+ }
2536
+ buildConstraints() {
2537
+ const expressionOne = new Expression(this.elementOne[ySymbol]).plus(new Expression(this.elementOne[heightSymbol]).multiply(this.parameters.anchorOne));
2538
+ const expressionTwo = new Expression(this.elementTwo[ySymbol]).plus(new Expression(this.elementTwo[heightSymbol]).multiply(this.parameters.anchorTwo));
2539
+ this.constraint = new Constraint(expressionTwo.minus(expressionOne), convertRuleToOperator(this.parameters.rule), this.parameters.distance, convertPowerToStrength(this.parameters.power));
2540
+ this.layer[addConstraintSymbol](this, this.constraint);
2541
+ }
2542
+ destroyConstraints() {
2543
+ if (this.constraint) {
2544
+ this.layer[removeConstraintSymbol](this, this.constraint);
2545
+ this.constraint = undefined;
2546
+ }
2547
+ }
2548
+ }
2549
+
2550
+ class UIVerticalProportionConstraint extends UIConstraint {
2551
+ constructor(elementOne, elementTwo, parameters) {
2552
+ var _a;
2553
+ assertSameLayer(elementOne, elementTwo);
2554
+ super(elementTwo.layer, new Set(elementOne instanceof UIElement
2555
+ ? [elementOne, elementTwo]
2556
+ : [elementTwo]));
2557
+ this.elementOne = elementOne;
2558
+ this.elementTwo = elementTwo;
2559
+ this.parameters = {
2560
+ proportion: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.proportion) !== null && _a !== void 0 ? _a : 1,
2561
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
2562
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
2563
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2564
+ };
2565
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2566
+ this.parameters.orientation === this.layer.orientation) {
2567
+ this.buildConstraints();
2568
+ }
2569
+ }
2570
+ destroy() {
2571
+ this.destroyConstraints();
2572
+ super.destroy();
2573
+ }
2574
+ [disableConstraintSymbol](orientation) {
2575
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2576
+ orientation !== this.parameters.orientation) {
2577
+ this.destroyConstraints();
2578
+ }
2579
+ }
2580
+ [enableConstraintSymbol](orientation) {
2581
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2582
+ orientation === this.parameters.orientation) {
2583
+ this.buildConstraints();
2584
+ }
2585
+ }
2586
+ buildConstraints() {
2587
+ const expressionOne = new Expression(this.elementOne[heightSymbol]).multiply(this.parameters.proportion);
2588
+ const expressionTwo = new Expression(this.elementTwo[heightSymbol]);
2589
+ this.constraint = new Constraint(expressionOne.minus(expressionTwo), convertRuleToOperator(this.parameters.rule), 0, convertPowerToStrength(this.parameters.power));
2590
+ this.layer[addConstraintSymbol](this, this.constraint);
2591
+ }
2592
+ destroyConstraints() {
2593
+ if (this.constraint) {
2594
+ this.layer[removeConstraintSymbol](this, this.constraint);
2595
+ this.constraint = undefined;
2596
+ }
2597
+ }
2598
+ }
2599
+
2600
+ class UIWidthConstraint extends UIConstraint {
2601
+ constructor(element, parameters) {
2602
+ var _a;
2603
+ super(element.layer, new Set([element]));
2604
+ this.element = element;
2605
+ this.parameters = {
2606
+ width: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.width) !== null && _a !== void 0 ? _a : 100,
2607
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
2608
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
2609
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2610
+ };
2611
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2612
+ this.parameters.orientation === this.layer.orientation) {
2613
+ this.buildConstraints();
2614
+ }
2615
+ }
2616
+ destroy() {
2617
+ this.destroyConstraints();
2618
+ super.destroy();
2619
+ }
2620
+ [disableConstraintSymbol](orientation) {
2621
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2622
+ orientation !== this.parameters.orientation) {
2623
+ this.destroyConstraints();
2624
+ }
2625
+ }
2626
+ [enableConstraintSymbol](orientation) {
2627
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2628
+ orientation === this.parameters.orientation) {
2629
+ this.buildConstraints();
2630
+ }
2631
+ }
2632
+ buildConstraints() {
2633
+ this.constraint = new Constraint(new Expression(this.element[widthSymbol]), convertRuleToOperator(this.parameters.rule), this.parameters.width, convertPowerToStrength(this.parameters.power));
2634
+ this.layer[addConstraintSymbol](this, this.constraint);
2635
+ }
2636
+ destroyConstraints() {
2637
+ if (this.constraint) {
2638
+ this.layer[removeConstraintSymbol](this, this.constraint);
2639
+ this.constraint = undefined;
2640
+ }
2641
+ }
2642
+ }
2643
+
2644
+ class UIConstraintBuilder2D {
2645
+ static size2D(parameters) {
2646
+ return {
2647
+ width: new UIWidthConstraint(parameters.element, {
2648
+ width: parameters.width,
2649
+ power: parameters.powerHorizontal,
2650
+ rule: parameters.ruleHorizontal,
2651
+ orientation: parameters.orientationHorizontal,
2652
+ }),
2653
+ height: new UIHeightConstraint(parameters.element, {
2654
+ height: parameters.height,
2655
+ power: parameters.powerVertical,
2656
+ rule: parameters.ruleVertical,
2657
+ orientation: parameters.orientationVertical,
2658
+ }),
2659
+ };
2660
+ }
2661
+ static distance2D(parameters) {
2662
+ return {
2663
+ horizontal: new UIHorizontalDistanceConstraint(parameters.elementOne, parameters.elementTwo, {
2664
+ anchorOne: parameters.anchorHorizontalOne,
2665
+ anchorTwo: parameters.anchorHorizontalTwo,
2666
+ distance: parameters.distanceHorizontal,
2667
+ power: parameters.powerHorizontal,
2668
+ rule: parameters.ruleHorizontal,
2669
+ orientation: parameters.orientationHorizontal,
2670
+ }),
2671
+ vertical: new UIVerticalDistanceConstraint(parameters.elementOne, parameters.elementTwo, {
2672
+ anchorOne: parameters.anchorVerticalOne,
2673
+ anchorTwo: parameters.anchorVerticalTwo,
2674
+ distance: parameters.distanceVertical,
2675
+ power: parameters.powerVertical,
2676
+ rule: parameters.ruleVertical,
2677
+ orientation: parameters.orientationVertical,
2678
+ }),
2679
+ };
2680
+ }
2681
+ static proportional2D(parameters) {
2682
+ return {
2683
+ horizontal: new UIHorizontalProportionConstraint(parameters.elementOne, parameters.elementTwo, {
2684
+ proportion: parameters.proportionHorizontal,
2685
+ power: parameters.powerHorizontal,
2686
+ rule: parameters.ruleHorizontal,
2687
+ orientation: parameters.orientationHorizontal,
2688
+ }),
2689
+ vertical: new UIVerticalProportionConstraint(parameters.elementOne, parameters.elementTwo, {
2690
+ proportion: parameters.proportionVertical,
2691
+ power: parameters.powerVertical,
2692
+ rule: parameters.ruleVertical,
2693
+ orientation: parameters.orientationVertical,
2694
+ }),
2695
+ };
2696
+ }
2697
+ }
2698
+
2699
+ class UIAspectConstraint extends UIConstraint {
2700
+ constructor(element, parameters) {
2701
+ var _a;
2702
+ super(element.layer, new Set([element]));
2703
+ this.element = element;
2704
+ this.parameters = {
2705
+ aspect: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.aspect) !== null && _a !== void 0 ? _a : this.element.width / this.element.height,
2706
+ power: resolvePower(parameters === null || parameters === void 0 ? void 0 : parameters.power),
2707
+ rule: resolveRule(parameters === null || parameters === void 0 ? void 0 : parameters.rule),
2708
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2709
+ };
2710
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2711
+ this.parameters.orientation === this.layer.orientation) {
2712
+ this.buildConstraints();
2713
+ }
2714
+ }
2715
+ destroy() {
2716
+ this.destroyConstraints();
2717
+ super.destroy();
2718
+ }
2719
+ [disableConstraintSymbol](newOrientation) {
2720
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2721
+ newOrientation !== this.parameters.orientation) {
2722
+ this.destroyConstraints();
2723
+ }
2724
+ }
2725
+ [enableConstraintSymbol](newOrientation) {
2726
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2727
+ newOrientation === this.parameters.orientation) {
2728
+ this.buildConstraints();
2729
+ }
2730
+ }
2731
+ buildConstraints() {
2732
+ const expression = new Expression(this.element[widthSymbol]).plus(new Expression(this.element[heightSymbol]).multiply(-this.parameters.aspect));
2733
+ this.constraint = new Constraint(expression, convertRuleToOperator(this.parameters.rule), 0, convertPowerToStrength(this.parameters.power));
2734
+ this.layer[addConstraintSymbol](this, this.constraint);
2735
+ }
2736
+ destroyConstraints() {
2737
+ if (this.constraint) {
2738
+ this.layer[removeConstraintSymbol](this, this.constraint);
2739
+ this.constraint = undefined;
2740
+ }
2741
+ }
2742
+ }
2743
+
2744
+ class UICoverConstraint extends UIConstraint {
2745
+ constructor(elementOne, elementTwo, parameters) {
2746
+ var _a, _b, _c;
2747
+ assertSameLayer(elementOne, elementTwo);
2748
+ super(elementTwo.layer, new Set(elementOne instanceof UIElement
2749
+ ? [elementOne, elementTwo]
2750
+ : [elementTwo]));
2751
+ this.elementOne = elementOne;
2752
+ this.elementTwo = elementTwo;
2753
+ this.parameters = {
2754
+ isStrict: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.isStrict) !== null && _a !== void 0 ? _a : true,
2755
+ horizontalAnchor: (_b = parameters === null || parameters === void 0 ? void 0 : parameters.horizontalAnchor) !== null && _b !== void 0 ? _b : 0.5,
2756
+ verticalAnchor: (_c = parameters === null || parameters === void 0 ? void 0 : parameters.verticalAnchor) !== null && _c !== void 0 ? _c : 0.5,
2757
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
2758
+ };
2759
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
2760
+ this.parameters.orientation === this.layer.orientation) {
2761
+ this.buildConstraints();
2762
+ }
2763
+ }
2764
+ destroy() {
2765
+ this.destroyConstraints();
2766
+ super.destroy();
2767
+ }
2768
+ [disableConstraintSymbol](orientation) {
2769
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2770
+ orientation !== this.parameters.orientation) {
2771
+ this.destroyConstraints();
2772
+ }
2773
+ }
2774
+ [enableConstraintSymbol](orientation) {
2775
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
2776
+ orientation === this.parameters.orientation) {
2777
+ this.buildConstraints();
2778
+ }
2779
+ }
2780
+ buildConstraints() {
2781
+ this.constraintX = new Constraint(new Expression(this.elementOne[xSymbol]).plus(new Expression(this.elementOne[widthSymbol]).multiply(this.parameters.horizontalAnchor)), Operator.Eq, new Expression(this.elementTwo[xSymbol]).plus(new Expression(this.elementTwo[widthSymbol]).multiply(this.parameters.horizontalAnchor)));
2782
+ this.constraintY = new Constraint(new Expression(this.elementOne[ySymbol]).plus(new Expression(this.elementOne[heightSymbol]).multiply(this.parameters.verticalAnchor)), Operator.Eq, new Expression(this.elementTwo[ySymbol]).plus(new Expression(this.elementTwo[heightSymbol]).multiply(this.parameters.verticalAnchor)));
2783
+ this.constraintW = new Constraint(new Expression(this.elementOne[widthSymbol]), Operator.Le, new Expression(this.elementTwo[widthSymbol]));
2784
+ this.constraintH = new Constraint(new Expression(this.elementOne[heightSymbol]), Operator.Le, new Expression(this.elementTwo[heightSymbol]));
2785
+ this.layer[addConstraintSymbol](this, this.constraintX);
2786
+ this.layer[addConstraintSymbol](this, this.constraintY);
2787
+ this.layer[addConstraintSymbol](this, this.constraintW);
2788
+ this.layer[addConstraintSymbol](this, this.constraintH);
2789
+ if (!this.parameters.isStrict) {
2790
+ this.constraintStrict = new Constraint(new Expression(this.elementOne[heightSymbol]), Operator.Eq, new Expression(this.elementTwo[heightSymbol]), Strength.strong);
2791
+ this.layer[addConstraintSymbol](this, this.constraintStrict);
2792
+ }
2793
+ }
2794
+ destroyConstraints() {
2795
+ if (this.constraintX) {
2796
+ this.layer[removeConstraintSymbol](this, this.constraintX);
2797
+ this.constraintX = undefined;
2798
+ }
2799
+ if (this.constraintY) {
2800
+ this.layer[removeConstraintSymbol](this, this.constraintY);
2801
+ this.constraintY = undefined;
2802
+ }
2803
+ if (this.constraintW) {
2804
+ this.layer[removeConstraintSymbol](this, this.constraintW);
2805
+ this.constraintW = undefined;
2806
+ }
2807
+ if (this.constraintH) {
2808
+ this.layer[removeConstraintSymbol](this, this.constraintH);
2809
+ this.constraintH = undefined;
2810
+ }
2811
+ if (this.constraintStrict) {
2812
+ this.layer[removeConstraintSymbol](this, this.constraintStrict);
2813
+ this.constraintStrict = undefined;
2814
+ }
2815
+ }
2816
+ }
2817
+
2818
+ function isAtLeastOneNumber(obj) {
2819
+ return (obj !== null &&
2820
+ typeof obj === "object" &&
2821
+ (("x" in obj && typeof obj.x === "number") ||
2822
+ ("y" in obj && typeof obj.y === "number")));
2823
+ }
2824
+ function isAtLeastOnePower(obj) {
2825
+ return (obj !== null &&
2826
+ typeof obj === "object" &&
2827
+ (("x" in obj && isUIConstraintPower(obj.x)) ||
2828
+ ("y" in obj && isUIConstraintPower(obj.y))));
2829
+ }
2830
+ function isAtLeastOneRule(obj) {
2831
+ return (obj !== null &&
2832
+ typeof obj === "object" &&
2833
+ (("x" in obj && isUIConstraintRule(obj.x)) ||
2834
+ ("y" in obj && isUIConstraintRule(obj.y))));
2835
+ }
2836
+ function isUICommonDoubleElementConstraintDescription(obj) {
2837
+ return (obj !== null &&
2838
+ typeof obj === "object" &&
2839
+ "elementOne" in obj &&
2840
+ "elementTwo" in obj &&
2841
+ (obj.elementOne instanceof UIElement ||
2842
+ obj.elementOne instanceof UILayer) &&
2843
+ obj.elementTwo instanceof UIElement);
2844
+ }
2845
+ function isUICommonDistanceConstraintDescription(obj) {
2846
+ return (isUICommonDoubleElementConstraintDescription(obj) &&
2847
+ "distance" in obj &&
2848
+ isAtLeastOneNumber(obj.distance) &&
2849
+ (!("anchorOne" in obj) ||
2850
+ ("anchorOne" in obj && isAtLeastOneNumber(obj.anchorOne))) &&
2851
+ (!("anchorTwo" in obj) ||
2852
+ ("anchorTwo" in obj && isAtLeastOneNumber(obj.anchorTwo))) &&
2853
+ (!("power" in obj) || isAtLeastOnePower(obj.power)) &&
2854
+ (!("rule" in obj) || isAtLeastOneRule(obj.rule)) &&
2855
+ (!("orientation" in obj) || isUIOrientation(obj.orientation)));
2856
+ }
2857
+ function isUICommonProportionalConstraintDescription(obj) {
2858
+ return (isUICommonDoubleElementConstraintDescription(obj) &&
2859
+ "proportion" in obj &&
2860
+ isAtLeastOneNumber(obj.proportion) &&
2861
+ (!("power" in obj) || isAtLeastOnePower(obj.power)) &&
2862
+ (!("rule" in obj) || isAtLeastOneRule(obj.rule)) &&
2863
+ (!("orientation" in obj) || isUIOrientation(obj.orientation)));
2864
+ }
2865
+ function isUICommonCoverConstraintDescription(obj) {
2866
+ return (isUICommonDoubleElementConstraintDescription(obj) &&
2867
+ "isStrict" in obj &&
2868
+ typeof obj.isStrict === "boolean" &&
2869
+ (!("anchor" in obj) || ("anchor" in obj && isAtLeastOneNumber(obj.anchor))));
2870
+ }
2871
+
2872
+ function isUICommonSingleElementConstraintDescription(obj) {
2873
+ return (obj !== null &&
2874
+ typeof obj === "object" &&
2875
+ "element" in obj &&
2876
+ obj.element instanceof UIElement &&
2877
+ (!("power" in obj) || isUIConstraintPower(obj.power)) &&
2878
+ (!("rule" in obj) || isUIConstraintRule(obj.rule)));
2879
+ }
2880
+ function isUIWidthConstraintDescription(obj) {
2881
+ return (isUICommonSingleElementConstraintDescription(obj) &&
2882
+ "width" in obj &&
2883
+ typeof obj.width === "number");
2884
+ }
2885
+ function isUIHeightConstraintDescription(obj) {
2886
+ return (isUICommonSingleElementConstraintDescription(obj) &&
2887
+ "height" in obj &&
2888
+ typeof obj.height === "number");
2889
+ }
2890
+ function isUIKeepAspectConstraintDescription(obj) {
2891
+ return (isUICommonSingleElementConstraintDescription(obj) &&
2892
+ "keepAspect" in obj &&
2893
+ typeof obj.keepAspect === "boolean");
2894
+ }
2895
+ function isUIKeepSizeConstraintDescription(obj) {
2896
+ return (isUICommonSingleElementConstraintDescription(obj) &&
2897
+ "keepSize" in obj &&
2898
+ typeof obj.keepSize === "boolean");
2899
+ }
2900
+
2901
+ class UIConstraintBuilder {
2902
+ static fromDescription(description) {
2903
+ const entries = description instanceof Map
2904
+ ? description.entries()
2905
+ : Object.entries(description);
2906
+ const constraints = new Map();
2907
+ for (const [key, value] of entries) {
2908
+ if (constraints.has(key)) {
2909
+ throw new Error(`Duplicate constraint key "${key}" - each constraint must have a unique identifier`);
2910
+ }
2911
+ if (isUIWidthConstraintDescription(value)) {
2912
+ UIConstraintBuilder.buildWidthConstraint(key, value, constraints);
2913
+ }
2914
+ else if (isUIHeightConstraintDescription(value)) {
2915
+ UIConstraintBuilder.buildHeightConstraint(key, value, constraints);
2916
+ }
2917
+ else if (isUIKeepAspectConstraintDescription(value)) {
2918
+ UIConstraintBuilder.buildKeepAspectConstraint(key, value, constraints);
2919
+ }
2920
+ else if (isUIKeepSizeConstraintDescription(value)) {
2921
+ UIConstraintBuilder.buildKeepSizeConstraint(key, value, constraints);
2922
+ }
2923
+ else if (isUICommonDistanceConstraintDescription(value)) {
2924
+ UIConstraintBuilder.buildDistanceConstraint(key, value, constraints);
2925
+ }
2926
+ else if (isUICommonProportionalConstraintDescription(value)) {
2927
+ UIConstraintBuilder.buildProportionalConstraint(key, value, constraints);
2928
+ }
2929
+ else if (isUICommonCoverConstraintDescription(value)) {
2930
+ UIConstraintBuilder.buildCoverConstraint(key, value, constraints);
2931
+ }
2932
+ else {
2933
+ throw new Error(`Invalid constraint type for "${key}". Expected one of: Width, Height, KeepAspect, KeepSize, Distance, Proportional, or Cover constraint`);
2934
+ }
2935
+ }
2936
+ return Object.fromEntries(constraints);
2937
+ }
2938
+ static buildWidthConstraint(key, value, constraints) {
2939
+ constraints.set(key, new UIWidthConstraint(value.element, {
2940
+ width: value.width,
2941
+ power: value.power,
2942
+ rule: value.rule,
2943
+ orientation: value.orientation,
2944
+ }));
2945
+ }
2946
+ static buildHeightConstraint(key, value, constraints) {
2947
+ constraints.set(key, new UIHeightConstraint(value.element, {
2948
+ height: value.height,
2949
+ power: value.power,
2950
+ rule: value.rule,
2951
+ orientation: value.orientation,
2952
+ }));
2953
+ }
2954
+ static buildKeepAspectConstraint(key, value, constraints) {
2955
+ constraints.set(key, new UIAspectConstraint(value.element, {
2956
+ power: value.power,
2957
+ rule: value.rule,
2958
+ orientation: value.orientation,
2959
+ }));
2960
+ }
2961
+ static buildKeepSizeConstraint(key, value, constraints) {
2962
+ const newKeyWidth = key.replace(/(KeepSize|Keep)$/, "") + "KeepWidth";
2963
+ const newKeyHeight = key.replace(/(KeepSize|Keep)$/, "") + "KeepHeight";
2964
+ constraints.set(newKeyWidth, new UIWidthConstraint(value.element, {
2965
+ power: value.power,
2966
+ rule: value.rule,
2967
+ orientation: value.orientation,
2968
+ }));
2969
+ constraints.set(newKeyHeight, new UIHeightConstraint(value.element, {
2970
+ power: value.power,
2971
+ rule: value.rule,
2972
+ orientation: value.orientation,
2973
+ }));
2974
+ }
2975
+ static buildDistanceConstraint(key, value, constraints) {
2976
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2977
+ if (typeof value.distance.x === "number") {
2978
+ const newKey = key.replace(/(HorizontalDistance|Distance)$/, "") +
2979
+ "HorizontalDistance";
2980
+ constraints.set(newKey, new UIHorizontalDistanceConstraint(value.elementOne, value.elementTwo, {
2981
+ distance: value.distance.x,
2982
+ anchorOne: (_a = value.anchorOne) === null || _a === void 0 ? void 0 : _a.x,
2983
+ anchorTwo: (_b = value.anchorTwo) === null || _b === void 0 ? void 0 : _b.x,
2984
+ power: (_c = value.power) === null || _c === void 0 ? void 0 : _c.x,
2985
+ rule: (_d = value.rule) === null || _d === void 0 ? void 0 : _d.x,
2986
+ orientation: value.orientation,
2987
+ }));
2988
+ }
2989
+ if (typeof value.distance.y === "number") {
2990
+ const newKey = key.replace(/(VerticalDistance|Distance)$/, "") + "VerticalDistance";
2991
+ constraints.set(newKey, new UIVerticalDistanceConstraint(value.elementOne, value.elementTwo, {
2992
+ distance: value.distance.y,
2993
+ anchorOne: (_e = value.anchorOne) === null || _e === void 0 ? void 0 : _e.y,
2994
+ anchorTwo: (_f = value.anchorTwo) === null || _f === void 0 ? void 0 : _f.y,
2995
+ power: (_g = value.power) === null || _g === void 0 ? void 0 : _g.y,
2996
+ rule: (_h = value.rule) === null || _h === void 0 ? void 0 : _h.y,
2997
+ orientation: value.orientation,
2998
+ }));
2999
+ }
3000
+ }
3001
+ static buildProportionalConstraint(key, value, constraints) {
3002
+ var _a, _b, _c, _d;
3003
+ if (typeof value.proportion.x === "number") {
3004
+ const newKey = key.replace(/(HorizontalProportional|HorizontalProportion|Proportional|Proportion)$/, "") + "HorizontalProportion";
3005
+ constraints.set(newKey, new UIHorizontalProportionConstraint(value.elementOne, value.elementTwo, {
3006
+ proportion: value.proportion.x,
3007
+ power: (_a = value.power) === null || _a === void 0 ? void 0 : _a.x,
3008
+ rule: (_b = value.rule) === null || _b === void 0 ? void 0 : _b.x,
3009
+ orientation: value.orientation,
3010
+ }));
3011
+ }
3012
+ if (typeof value.proportion.y === "number") {
3013
+ const newKey = key.replace(/(VerticalProportional|VerticalProportion|Proportional|Proportion)$/, "") + "VerticalProportion";
3014
+ constraints.set(newKey, new UIVerticalProportionConstraint(value.elementOne, value.elementTwo, {
3015
+ proportion: value.proportion.y,
3016
+ power: (_c = value.power) === null || _c === void 0 ? void 0 : _c.y,
3017
+ rule: (_d = value.rule) === null || _d === void 0 ? void 0 : _d.y,
3018
+ orientation: value.orientation,
3019
+ }));
3020
+ }
3021
+ }
3022
+ static buildCoverConstraint(key, value, constraints) {
3023
+ var _a, _b;
3024
+ constraints.set(key, new UICoverConstraint(value.elementOne, value.elementTwo, {
3025
+ isStrict: value.isStrict,
3026
+ horizontalAnchor: (_a = value.anchor) === null || _a === void 0 ? void 0 : _a.x,
3027
+ verticalAnchor: (_b = value.anchor) === null || _b === void 0 ? void 0 : _b.y,
3028
+ }));
3029
+ }
3030
+ }
3031
+
3032
+ const DEFAULT_DUMMY_SIZE = 100;
3033
+ class UIDummy extends UIElement {
3034
+ constructor(layer, width = DEFAULT_DUMMY_SIZE, height = DEFAULT_DUMMY_SIZE) {
3035
+ super(layer, new Object3D(), 0, 0, width, height);
3036
+ this[flushTransformSymbol]();
3037
+ }
3038
+ }
3039
+
3040
+ class UIEnhancedMaterial {
3041
+ constructor(texture) {
3042
+ const uniforms = UniformsUtils.merge([
3043
+ {
3044
+ map: { value: texture },
3045
+ opacity: { value: 1.0 },
3046
+ color: { value: new Color(1.0, 1.0, 1.0) },
3047
+ uvTransform: { value: new Matrix3() },
3048
+ saturation: { value: 1.0 },
3049
+ brightness: { value: 1.0 },
3050
+ hue: { value: 0.0 },
3051
+ },
3052
+ ]);
3053
+ const vertexShader = /* glsl */ `
3054
+ uniform mat3 uvTransform;
3055
+ varying vec2 vUv;
3056
+ void main() {
3057
+ vUv = (uvTransform * vec3(uv, 1)).xy;
3058
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
3059
+ }
3060
+ `;
3061
+ const fragmentShader = /* glsl */ `
3062
+ uniform sampler2D map;
3063
+ uniform float opacity;
3064
+ uniform vec3 color;
3065
+ uniform float saturation;
3066
+ uniform float brightness;
3067
+ uniform float hue;
3068
+ varying vec2 vUv;
3069
+
3070
+ vec3 rgb2hsv(vec3 c) {
3071
+ vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
3072
+ vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
3073
+ vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
3074
+ float d = q.x - min(q.w, q.y);
3075
+ float e = 1.0e-10;
3076
+ return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
3077
+ }
3078
+
3079
+ vec3 hsv2rgb(vec3 c) {
3080
+ vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
3081
+ vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
3082
+ return c.z * mix(K.xxx, clamp(p - K. xxx, 0.0, 1.0), c.y);
3083
+ }
3084
+
3085
+ void main() {
3086
+ gl_FragColor = texture2D(map, vUv);
3087
+
3088
+ #include <colorspace_fragment>
3089
+
3090
+ vec3 hsv = rgb2hsv(gl_FragColor.rgb);
3091
+
3092
+ hsv.x = fract(hsv.x + hue);
3093
+ hsv.y = clamp(hsv.y * saturation, 0.0, 1.0);
3094
+ hsv.z = hsv.z * brightness;
3095
+
3096
+ vec3 rgb = hsv2rgb(hsv);
3097
+ gl_FragColor = vec4(rgb * color, gl_FragColor.a * opacity);
3098
+ }
3099
+ `;
3100
+ this[materialSymbol] = new ShaderMaterial({
3101
+ uniforms,
3102
+ vertexShader,
3103
+ fragmentShader,
3104
+ transparent: true,
3105
+ fog: false,
3106
+ lights: false,
3107
+ });
3108
+ }
3109
+ get color() {
3110
+ return this[materialSymbol].uniforms.color.value;
3111
+ }
3112
+ get opacity() {
3113
+ return this[materialSymbol].uniforms.opacity.value;
3114
+ }
3115
+ get saturation() {
3116
+ return this[materialSymbol].uniforms.saturation.value;
3117
+ }
3118
+ get brightness() {
3119
+ return this[materialSymbol].uniforms.brightness.value;
3120
+ }
3121
+ get hue() {
3122
+ return this[materialSymbol].uniforms.hue.value;
3123
+ }
3124
+ set color(value) {
3125
+ this[materialSymbol].uniforms.color.value = value;
3126
+ }
3127
+ set saturation(value) {
3128
+ this[materialSymbol].uniforms.saturation.value = value;
3129
+ }
3130
+ set brightness(value) {
3131
+ this[materialSymbol].uniforms.brightness.value = value;
3132
+ }
3133
+ set hue(value) {
3134
+ this[materialSymbol].uniforms.hue.value = value;
3135
+ }
3136
+ set opacity(value) {
3137
+ this[materialSymbol].uniforms.opacity.value = value;
3138
+ }
3139
+ }
3140
+
3141
+ const GEOMETRY_SIZE = 1;
3142
+ const GEOMETRY_OFFSET = 0.5;
3143
+ const geometry = new PlaneGeometry(GEOMETRY_SIZE, GEOMETRY_SIZE).translate(GEOMETRY_OFFSET, GEOMETRY_OFFSET, 0);
3144
+
3145
+ class UIImage extends UIElement {
3146
+ constructor(layer, texture) {
3147
+ var _a, _b;
3148
+ const width = (_a = texture.image) === null || _a === void 0 ? void 0 : _a.width;
3149
+ const height = (_b = texture.image) === null || _b === void 0 ? void 0 : _b.height;
3150
+ assertSize(width, height, `Invalid image dimensions - texture "${texture.name || "unnamed"}" has invalid width (${width}) or height (${height}). Image dimensions must be non-zero positive numbers.`);
3151
+ const material = new UIEnhancedMaterial(texture);
3152
+ const object = new Mesh(geometry, material[materialSymbol]);
3153
+ super(layer, object, 0, 0, width, height);
3154
+ this.material = material;
3155
+ this[flushTransformSymbol]();
3156
+ }
3157
+ destroy() {
3158
+ this.material[materialSymbol].dispose();
3159
+ super.destroy();
3160
+ }
3161
+ }
3162
+
3163
+ function resolvePadding(padding) {
3164
+ var _a, _b, _c, _d;
3165
+ if (typeof padding === "number") {
3166
+ return {
3167
+ left: padding,
3168
+ right: padding,
3169
+ top: padding,
3170
+ bottom: padding,
3171
+ };
3172
+ }
3173
+ return {
3174
+ left: Math.max((_a = padding === null || padding === void 0 ? void 0 : padding.left) !== null && _a !== void 0 ? _a : 0, 0),
3175
+ right: Math.max((_b = padding === null || padding === void 0 ? void 0 : padding.right) !== null && _b !== void 0 ? _b : 0, 0),
3176
+ top: Math.max((_c = padding === null || padding === void 0 ? void 0 : padding.top) !== null && _c !== void 0 ? _c : 0, 0),
3177
+ bottom: Math.max((_d = padding === null || padding === void 0 ? void 0 : padding.bottom) !== null && _d !== void 0 ? _d : 0, 0),
3178
+ };
3179
+ }
3180
+ function resolveTextStyle(currentStyle, baseStyle) {
3181
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3;
3182
+ const fontSize = Math.max((_b = (_a = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.fontSize) !== null && _a !== void 0 ? _a : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.fontSize) !== null && _b !== void 0 ? _b : 16, 1);
3183
+ const lineHeight = (_d = (_c = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.lineHeight) !== null && _c !== void 0 ? _c : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.lineHeight) !== null && _d !== void 0 ? _d : fontSize * 1.2;
3184
+ const shadowBlur = Math.max((_f = (_e = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.shadowBlur) !== null && _e !== void 0 ? _e : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.shadowBlur) !== null && _f !== void 0 ? _f : 0, 0);
3185
+ const strokeWidth = Math.max((_h = (_g = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.strokeWidth) !== null && _g !== void 0 ? _g : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.strokeWidth) !== null && _h !== void 0 ? _h : 0, 0);
3186
+ return {
3187
+ color: (_k = (_j = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.color) !== null && _j !== void 0 ? _j : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.color) !== null && _k !== void 0 ? _k : "#000000",
3188
+ fontFamily: (_m = (_l = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.fontFamily) !== null && _l !== void 0 ? _l : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.fontFamily) !== null && _m !== void 0 ? _m : "Arial",
3189
+ fontSize,
3190
+ fontStyle: (_p = (_o = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.fontStyle) !== null && _o !== void 0 ? _o : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.fontStyle) !== null && _p !== void 0 ? _p : "normal",
3191
+ fontWeight: (_r = (_q = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.fontWeight) !== null && _q !== void 0 ? _q : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.fontWeight) !== null && _r !== void 0 ? _r : "normal",
3192
+ lineHeight,
3193
+ enableShadow: (_t = (_s = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.enableShadow) !== null && _s !== void 0 ? _s : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.enableShadow) !== null && _t !== void 0 ? _t : false,
3194
+ shadowOffsetX: (_v = (_u = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.shadowOffsetX) !== null && _u !== void 0 ? _u : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.shadowOffsetX) !== null && _v !== void 0 ? _v : 0,
3195
+ shadowOffsetY: (_x = (_w = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.shadowOffsetY) !== null && _w !== void 0 ? _w : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.shadowOffsetY) !== null && _x !== void 0 ? _x : 0,
3196
+ shadowBlur,
3197
+ shadowColor: (_z = (_y = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.shadowColor) !== null && _y !== void 0 ? _y : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.shadowColor) !== null && _z !== void 0 ? _z : "transparent",
3198
+ enableStroke: (_1 = (_0 = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.enableStroke) !== null && _0 !== void 0 ? _0 : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.enableStroke) !== null && _1 !== void 0 ? _1 : false,
3199
+ strokeColor: (_3 = (_2 = currentStyle === null || currentStyle === void 0 ? void 0 : currentStyle.strokeColor) !== null && _2 !== void 0 ? _2 : baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.strokeColor) !== null && _3 !== void 0 ? _3 : "transparent",
3200
+ strokeWidth,
3201
+ };
3202
+ }
3203
+ function splitText(text) {
3204
+ return text.match(/\S+|\s|\n/g) || [];
3205
+ }
3206
+ function measureTextChunk(context, chunk, style) {
3207
+ context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize}px ${style.fontFamily}`;
3208
+ if (chunk === "\n") {
3209
+ return {
3210
+ width: Math.ceil(0),
3211
+ height: style.lineHeight,
3212
+ baseline: 0,
3213
+ lineHeight: style.lineHeight,
3214
+ };
3215
+ }
3216
+ const metrics = context.measureText(chunk);
3217
+ const width = metrics.width;
3218
+ const height = Math.ceil(metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent);
3219
+ return {
3220
+ width: Math.ceil(width),
3221
+ height: height,
3222
+ baseline: metrics.actualBoundingBoxDescent,
3223
+ lineHeight: style.lineHeight,
3224
+ };
3225
+ }
3226
+ function wrapTextLines(maxWidth, chunks) {
3227
+ const lines = [];
3228
+ let currentLine = [];
3229
+ let currentWidth = 0;
3230
+ let currentHeight = 0;
3231
+ let currentBaseline = 0;
3232
+ let currentLineHeight = 0;
3233
+ for (const chunk of chunks) {
3234
+ if (chunk.text === "\n") {
3235
+ if (currentLine.length > 0) {
3236
+ lines.push({
3237
+ chunks: currentLine,
3238
+ width: currentWidth,
3239
+ height: currentHeight,
3240
+ baseline: currentBaseline,
3241
+ lineHeight: currentLineHeight,
3242
+ });
3243
+ }
3244
+ currentLine = [];
3245
+ currentWidth = 0;
3246
+ currentHeight = 0;
3247
+ currentBaseline = 0;
3248
+ currentLineHeight = 0;
3249
+ continue;
3250
+ }
3251
+ if (currentWidth + chunk.metrics.width <= maxWidth ||
3252
+ currentLine.length === 0) {
3253
+ currentLine.push(chunk);
3254
+ currentWidth += chunk.metrics.width;
3255
+ currentHeight = Math.max(currentHeight, chunk.metrics.height);
3256
+ currentBaseline = Math.max(currentBaseline, chunk.metrics.baseline);
3257
+ currentLineHeight = Math.max(currentLineHeight, chunk.metrics.lineHeight);
3258
+ }
3259
+ else {
3260
+ lines.push({
3261
+ chunks: currentLine,
3262
+ width: currentWidth,
3263
+ height: currentHeight,
3264
+ baseline: currentBaseline,
3265
+ lineHeight: currentLineHeight,
3266
+ });
3267
+ currentLine = [chunk];
3268
+ currentWidth = chunk.metrics.width;
3269
+ currentHeight = chunk.metrics.height;
3270
+ currentBaseline = chunk.metrics.baseline;
3271
+ currentLineHeight = chunk.metrics.lineHeight;
3272
+ }
3273
+ }
3274
+ if (currentLine.length > 0) {
3275
+ lines.push({
3276
+ chunks: currentLine,
3277
+ width: currentWidth,
3278
+ height: currentHeight,
3279
+ baseline: currentBaseline,
3280
+ lineHeight: currentLineHeight,
3281
+ });
3282
+ }
3283
+ return lines;
3284
+ }
3285
+ function calculateTextBlockSize(lines) {
3286
+ if (lines.length === 0) {
3287
+ return { width: 0, height: 0 };
3288
+ }
3289
+ const maxLineWidth = Math.max(...lines.map((line) => line.width));
3290
+ let totalHeight = 0;
3291
+ for (let i = 0; i < lines.length; i++) {
3292
+ const line = lines[i];
3293
+ if (i === 0) {
3294
+ totalHeight += line.height;
3295
+ }
3296
+ else {
3297
+ totalHeight += line.lineHeight;
3298
+ }
3299
+ if (i === lines.length - 1) {
3300
+ totalHeight += line.baseline;
3301
+ }
3302
+ }
3303
+ return {
3304
+ width: maxLineWidth,
3305
+ height: totalHeight,
3306
+ };
3307
+ }
3308
+ function renderText(x, y, text, style, context) {
3309
+ context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize}px ${style.fontFamily}`;
3310
+ if (style.enableShadow) {
3311
+ context.shadowOffsetX = style.shadowOffsetX;
3312
+ context.shadowOffsetY = style.shadowOffsetY;
3313
+ context.shadowBlur = style.shadowBlur;
3314
+ context.shadowColor = style.shadowColor;
3315
+ }
3316
+ if (style.enableStroke) {
3317
+ context.strokeStyle = style.strokeColor;
3318
+ context.lineWidth = style.strokeWidth;
3319
+ context.strokeText(text, x, y);
3320
+ }
3321
+ context.fillStyle = style.color;
3322
+ context.fillText(text, x, y);
3323
+ }
3324
+ function renderTextLines(paddingTop, paddingLeft, lines, context) {
3325
+ let currentY = paddingTop;
3326
+ for (let i = 0; i < lines.length; i++) {
3327
+ const line = lines[i];
3328
+ let currentX = paddingLeft;
3329
+ currentY += i === 0 ? line.height : line.lineHeight;
3330
+ for (const chunk of line.chunks) {
3331
+ renderText(currentX, currentY, chunk.text, chunk.style, context);
3332
+ currentX += chunk.metrics.width;
3333
+ }
3334
+ }
3335
+ }
3336
+
3337
+ class UIText extends UIElement {
3338
+ constructor(layer, spans, parameters = {}) {
3339
+ var _a;
3340
+ const canvas = document.createElement("canvas");
3341
+ const context = canvas.getContext("2d");
3342
+ if (!context) {
3343
+ throw new Error("Failed to create canvas context");
3344
+ }
3345
+ const chunks = [];
3346
+ for (const span of spans) {
3347
+ const isSpanString = typeof span === "string";
3348
+ const spanText = isSpanString ? span : span.text;
3349
+ const style = resolveTextStyle(isSpanString ? undefined : span.style, parameters.defaultStyle);
3350
+ for (const text of splitText(spanText)) {
3351
+ const metrics = measureTextChunk(context, text, style);
3352
+ chunks.push({ text, style, metrics });
3353
+ }
3354
+ }
3355
+ const wrappedLines = wrapTextLines((_a = parameters.maxWidth) !== null && _a !== void 0 ? _a : 1024, chunks);
3356
+ const textBlockSize = calculateTextBlockSize(wrappedLines);
3357
+ const padding = resolvePadding(parameters.padding);
3358
+ canvas.width = textBlockSize.width + padding.left + padding.right;
3359
+ canvas.height = textBlockSize.height + padding.top + padding.bottom;
3360
+ const texture = new CanvasTexture(canvas);
3361
+ const material = new UIEnhancedMaterial(texture);
3362
+ const object = new Mesh(geometry, material[materialSymbol]);
3363
+ super(layer, object, 0, 0, textBlockSize.width, textBlockSize.height);
3364
+ this.lastSuggestedAspect = 0;
3365
+ this.texture = texture;
3366
+ this.material = material;
3367
+ this.canvas = canvas;
3368
+ this.context = context;
3369
+ this.textBlockSize = textBlockSize;
3370
+ this.padding = padding;
3371
+ renderTextLines(this.padding.top, this.padding.left, wrappedLines, this.context);
3372
+ this.texture.needsUpdate = true;
3373
+ this[flushTransformSymbol]();
3374
+ }
3375
+ destroy() {
3376
+ this.material[materialSymbol].dispose();
3377
+ this.texture.dispose();
3378
+ this.canvas.remove();
3379
+ super.destroy();
3380
+ }
3381
+ [flushTransformSymbol]() {
3382
+ super[flushTransformSymbol]();
3383
+ const currentAspect = this.width / this.height;
3384
+ if (this.lastSuggestedAspect !== currentAspect) {
3385
+ this.lastSuggestedAspect = currentAspect;
3386
+ const targetAspect = (this.textBlockSize.width + this.padding.left + this.padding.right) /
3387
+ (this.textBlockSize.height + this.padding.top + this.padding.bottom);
3388
+ this.layer[suggestVariableSymbol](this, this[heightSymbol], this.width / targetAspect);
3389
+ }
3390
+ }
3391
+ }
3392
+
3393
+ function isUITextSpan(obj) {
3394
+ return (obj !== null &&
3395
+ typeof obj === "object" &&
3396
+ "text" in obj &&
3397
+ typeof obj.text === "string");
3398
+ }
3399
+
3400
+ function isUIImageDescription(obj) {
3401
+ return (obj !== null &&
3402
+ typeof obj === "object" &&
3403
+ "texture" in obj &&
3404
+ obj.texture instanceof Texture);
3405
+ }
3406
+ function isUITextDescription(obj) {
3407
+ return (obj !== null &&
3408
+ typeof obj === "object" &&
3409
+ "text" in obj &&
3410
+ typeof obj.text === "string");
3411
+ }
3412
+ function isUITextEnhancedDescription(obj) {
3413
+ return (obj !== null &&
3414
+ typeof obj === "object" &&
3415
+ "spans" in obj &&
3416
+ Array.isArray(obj.spans) &&
3417
+ obj.spans.every((span) => typeof span === "string" || isUITextSpan(span)));
3418
+ }
3419
+ function isUIDummyDescription(obj) {
3420
+ return (obj !== null &&
3421
+ typeof obj === "object" &&
3422
+ (!("width" in obj) || typeof obj.width === "number") &&
3423
+ (!("height" in obj) || typeof obj.height === "number"));
3424
+ }
3425
+
3426
+ class UIElementBuilder {
3427
+ static fromDescription(layer, description) {
3428
+ const entries = description instanceof Map
3429
+ ? description.entries()
3430
+ : Object.entries(description);
3431
+ const elements = new Map();
3432
+ for (const [key, value] of entries) {
3433
+ if (elements.has(key)) {
3434
+ throw new Error(`Duplicate element key "${key}" - each UI element must have a unique identifier`);
3435
+ }
3436
+ let element;
3437
+ if (value instanceof Texture) {
3438
+ element = new UIImage(layer, value);
3439
+ }
3440
+ else if (isUIImageDescription(value)) {
3441
+ element = new UIImage(layer, value.texture);
3442
+ }
3443
+ else if (typeof value === "string") {
3444
+ element = new UIText(layer, [value]);
3445
+ }
3446
+ else if (isUITextDescription(value)) {
3447
+ element = new UIText(layer, [value.text], {
3448
+ defaultStyle: value.style,
3449
+ });
3450
+ }
3451
+ else if (isUITextEnhancedDescription(value)) {
3452
+ element = new UIText(layer, value.spans, {
3453
+ defaultStyle: value.defaultStyle,
3454
+ });
3455
+ }
3456
+ else if (isUIDummyDescription(value)) {
3457
+ element = new UIDummy(layer, value.width, value.height);
3458
+ }
3459
+ else {
3460
+ throw new Error(`Invalid UI element type for "${key}". Expected one of: Texture, UIImage, String, UITextDescription, or UITextEnhancedDescription`);
3461
+ }
3462
+ elements.set(key, element);
3463
+ }
3464
+ return Object.fromEntries(elements);
3465
+ }
3466
+ }
3467
+
3468
+ class UIStackConstraintBuilder {
3469
+ static buildHorizontal(parameters) {
3470
+ const distanceConstraints = [];
3471
+ const proportionConstraints = [];
3472
+ const centerConstraints = [];
3473
+ for (let i = 0; i < parameters.elements.length - 1; i++) {
3474
+ const element = parameters.elements[i];
3475
+ const nextElement = parameters.elements[i + 1];
3476
+ distanceConstraints.push(new UIHorizontalDistanceConstraint(element, nextElement, {
3477
+ anchorOne: 1,
3478
+ anchorTwo: 0,
3479
+ distance: parameters.offset,
3480
+ power: parameters.power,
3481
+ }));
3482
+ proportionConstraints.push(new UIHorizontalProportionConstraint(element, nextElement, {
3483
+ power: parameters.power,
3484
+ }));
3485
+ if (parameters.keepAlignment !== false) {
3486
+ centerConstraints.push(new UIVerticalDistanceConstraint(element, nextElement, {
3487
+ power: parameters.power,
3488
+ anchorOne: 0,
3489
+ anchorTwo: 0,
3490
+ }));
3491
+ }
3492
+ }
3493
+ return {
3494
+ dummy: parameters.createDummy !== false
3495
+ ? UIStackConstraintBuilder.createDummy(parameters.elements[0], parameters.elements[parameters.elements.length - 1])
3496
+ : undefined,
3497
+ distanceConstraints,
3498
+ proportionConstraints,
3499
+ centerConstraints,
3500
+ };
3501
+ }
3502
+ static buildVertical(parameters) {
3503
+ const distanceConstraints = [];
3504
+ const proportionConstraints = [];
3505
+ const centerConstraints = [];
3506
+ for (let i = 0; i < parameters.elements.length - 1; i++) {
3507
+ const element = parameters.elements[i];
3508
+ const nextElement = parameters.elements[i + 1];
3509
+ distanceConstraints.push(new UIVerticalDistanceConstraint(element, nextElement, {
3510
+ anchorOne: 1,
3511
+ anchorTwo: 0,
3512
+ distance: parameters.offset,
3513
+ power: parameters.power,
3514
+ }));
3515
+ proportionConstraints.push(new UIVerticalProportionConstraint(element, nextElement, {
3516
+ power: parameters.power,
3517
+ }));
3518
+ if (parameters.keepAlignment !== false) {
3519
+ centerConstraints.push(new UIHorizontalDistanceConstraint(element, nextElement, {
3520
+ power: parameters.power,
3521
+ }));
3522
+ }
3523
+ }
3524
+ return {
3525
+ dummy: parameters.createDummy !== false
3526
+ ? UIStackConstraintBuilder.createDummy(parameters.elements[0], parameters.elements[parameters.elements.length - 1])
3527
+ : undefined,
3528
+ distanceConstraints,
3529
+ proportionConstraints,
3530
+ centerConstraints,
3531
+ };
3532
+ }
3533
+ static createDummy(firstElement, lastElement) {
3534
+ const dummy = new UIDummy(lastElement.layer);
3535
+ new UIHorizontalDistanceConstraint(dummy, firstElement, {
3536
+ distance: 0,
3537
+ anchorOne: 0,
3538
+ anchorTwo: 0,
3539
+ });
3540
+ new UIVerticalDistanceConstraint(dummy, firstElement, {
3541
+ distance: 0,
3542
+ anchorOne: 0,
3543
+ anchorTwo: 0,
3544
+ });
3545
+ new UIHorizontalDistanceConstraint(dummy, lastElement, {
3546
+ distance: 0,
3547
+ anchorOne: 1,
3548
+ anchorTwo: 1,
3549
+ });
3550
+ new UIVerticalDistanceConstraint(dummy, lastElement, {
3551
+ distance: 0,
3552
+ anchorOne: 1,
3553
+ anchorTwo: 1,
3554
+ });
3555
+ return dummy;
3556
+ }
3557
+ }
3558
+
3559
+ class UIFitConstraint extends UIConstraint {
3560
+ constructor(elementOne, elementTwo, parameters) {
3561
+ var _a, _b, _c;
3562
+ super(elementTwo.layer, new Set(elementOne instanceof UIElement
3563
+ ? [elementOne, elementTwo]
3564
+ : [elementTwo]));
3565
+ this.elementOne = elementOne;
3566
+ this.elementTwo = elementTwo;
3567
+ assertSameLayer(elementOne, elementTwo);
3568
+ this.parameters = {
3569
+ isStrict: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.isStrict) !== null && _a !== void 0 ? _a : true,
3570
+ horizontalAnchor: (_b = parameters === null || parameters === void 0 ? void 0 : parameters.horizontalAnchor) !== null && _b !== void 0 ? _b : 0.5,
3571
+ verticalAnchor: (_c = parameters === null || parameters === void 0 ? void 0 : parameters.verticalAnchor) !== null && _c !== void 0 ? _c : 0.5,
3572
+ orientation: resolveOrientation(parameters === null || parameters === void 0 ? void 0 : parameters.orientation),
3573
+ };
3574
+ if (this.parameters.orientation === UIOrientation.ALWAYS ||
3575
+ this.parameters.orientation === this.layer.orientation) {
3576
+ this.buildConstraints();
3577
+ }
3578
+ }
3579
+ destroy() {
3580
+ this.destroyConstraints();
3581
+ super.destroy();
3582
+ }
3583
+ [disableConstraintSymbol](orientation) {
3584
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
3585
+ orientation !== this.parameters.orientation) {
3586
+ this.destroyConstraints();
3587
+ }
3588
+ }
3589
+ [enableConstraintSymbol](orientation) {
3590
+ if (this.parameters.orientation !== UIOrientation.ALWAYS &&
3591
+ orientation === this.parameters.orientation) {
3592
+ this.buildConstraints();
3593
+ }
3594
+ }
3595
+ buildConstraints() {
3596
+ this.constraintX = new Constraint(new Expression(this.elementOne[xSymbol]).plus(new Expression(this.elementOne[widthSymbol]).multiply(this.parameters.horizontalAnchor)), Operator.Eq, new Expression(this.elementTwo[xSymbol]).plus(new Expression(this.elementTwo[widthSymbol]).multiply(this.parameters.horizontalAnchor)));
3597
+ this.constraintY = new Constraint(new Expression(this.elementOne[ySymbol]).plus(new Expression(this.elementOne[heightSymbol]).multiply(this.parameters.verticalAnchor)), Operator.Eq, new Expression(this.elementTwo[ySymbol]).plus(new Expression(this.elementTwo[heightSymbol]).multiply(this.parameters.verticalAnchor)));
3598
+ this.constraintW = new Constraint(new Expression(this.elementOne[widthSymbol]), Operator.Ge, new Expression(this.elementTwo[widthSymbol]));
3599
+ this.constraintH = new Constraint(new Expression(this.elementOne[heightSymbol]), Operator.Ge, new Expression(this.elementTwo[heightSymbol]));
3600
+ this.layer[addConstraintSymbol](this, this.constraintX);
3601
+ this.layer[addConstraintSymbol](this, this.constraintY);
3602
+ this.layer[addConstraintSymbol](this, this.constraintW);
3603
+ this.layer[addConstraintSymbol](this, this.constraintH);
3604
+ if (this.parameters.isStrict !== false) {
3605
+ this.constraintStrict = new Constraint(new Expression(this.elementOne[heightSymbol]), Operator.Eq, new Expression(this.elementTwo[heightSymbol]), Strength.strong);
3606
+ this.layer[addConstraintSymbol](this, this.constraintStrict);
3607
+ }
3608
+ }
3609
+ destroyConstraints() {
3610
+ if (this.constraintX) {
3611
+ this.layer[removeConstraintSymbol](this, this.constraintX);
3612
+ this.constraintX = undefined;
3613
+ }
3614
+ if (this.constraintY) {
3615
+ this.layer[removeConstraintSymbol](this, this.constraintY);
3616
+ this.constraintY = undefined;
3617
+ }
3618
+ if (this.constraintW) {
3619
+ this.layer[removeConstraintSymbol](this, this.constraintW);
3620
+ this.constraintW = undefined;
3621
+ }
3622
+ if (this.constraintH) {
3623
+ this.layer[removeConstraintSymbol](this, this.constraintH);
3624
+ this.constraintH = undefined;
3625
+ }
3626
+ if (this.constraintStrict) {
3627
+ this.layer[removeConstraintSymbol](this, this.constraintStrict);
3628
+ this.constraintStrict = undefined;
3629
+ }
3630
+ }
3631
+ }
3632
+
3633
+ const DEFAULT_SCREEN_HEIGHT = 1920;
3634
+ class UIFullScreenLayer extends UILayer {
3635
+ constructor() {
3636
+ super();
3637
+ this.targetScreenHeight = DEFAULT_SCREEN_HEIGHT;
3638
+ this.onResize = () => {
3639
+ const scale = this.calculateScale();
3640
+ this.resizeInternal(window.innerWidth * scale, window.innerHeight * scale);
3641
+ };
3642
+ this.onClick = (event) => {
3643
+ if (this.behavior !== UIBehavior.INTERACTIVE) {
3644
+ return;
3645
+ }
3646
+ const rect = event.target instanceof HTMLElement
3647
+ ? event.target.getBoundingClientRect()
3648
+ : null;
3649
+ const offsetX = rect ? event.clientX - rect.left : event.clientX;
3650
+ const offsetY = rect
3651
+ ? rect.bottom - event.clientY
3652
+ : window.innerHeight - event.clientY;
3653
+ const scale = this.calculateScale();
3654
+ this.clickInternal(offsetX * scale, offsetY * scale);
3655
+ };
3656
+ window.addEventListener("resize", this.onResize);
3657
+ window.addEventListener("click", this.onClick);
3658
+ this.onResize();
3659
+ }
3660
+ get tergetScreenHeight() {
3661
+ return this.targetScreenHeight;
3662
+ }
3663
+ set tergetScreenHeight(value) {
3664
+ this.targetScreenHeight = value;
3665
+ this.resizeInternal(window.innerWidth, window.innerHeight);
3666
+ }
3667
+ destroy() {
3668
+ window.removeEventListener("resize", this.onResize);
3669
+ window.removeEventListener("click", this.onClick);
3670
+ super.destroy();
3671
+ }
3672
+ calculateScale() {
3673
+ var _a;
3674
+ const targetHeight = (_a = this.tergetScreenHeight) !== null && _a !== void 0 ? _a : window.innerHeight;
3675
+ return targetHeight / window.innerHeight;
3676
+ }
3677
+ }
3678
+
3679
+ class UIManualLayer extends UILayer {
3680
+ click(x, y) {
3681
+ this.clickInternal(x, y);
3682
+ }
3683
+ resize(width, height) {
3684
+ this.resizeInternal(width, height);
3685
+ }
3686
+ }
3687
+
3688
+ export { UIAspectConstraint, UIBehavior, UIConstraintBuilder, UIConstraintBuilder2D, UIConstraintPower, UIConstraintRule, UICoverConstraint, UIDummy, UIElementBuilder, UIElementEvent, UIFitConstraint, UIFullScreenLayer, UIHeightConstraint, UIHorizontalDistanceConstraint, UIHorizontalProportionConstraint, UIImage, UIManualLayer, UIOrientation, UIStackConstraintBuilder, UIText, UIVerticalDistanceConstraint, UIVerticalProportionConstraint, UIWidthConstraint };
2
3689
  //# sourceMappingURL=index.js.map